diff --git a/tasks/livewire__livewire-10625/tests/test.sh b/tasks/livewire__livewire-10625/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..8757794d7ab211b54fff870746e8bfe0ab0dd3b4 --- /dev/null +++ b/tasks/livewire__livewire-10625/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 16f4c122578411fd4f8613a1d3b8bb4f30d8b38f > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/livewire__livewire-10625/tests/verifier.py b/tasks/livewire__livewire-10625/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/livewire__livewire-10625/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/livewire__livewire-10626/environment/Dockerfile b/tasks/livewire__livewire-10626/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cb36af0612f3f7e55f0ec9e499f93ab910e3b79a --- /dev/null +++ b/tasks/livewire__livewire-10626/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/livewire/livewire.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/livewire/livewire.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/livewire/livewire.git +WORKDIR /workspace +RUN git fetch --depth 1 origin db8815892bece057596cb5616ee15f6b42182bab 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard db8815892bece057596cb5616ee15f6b42182bab \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base db8815892bece057596cb5616ee15f6b42182bab \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/livewire__livewire-10626/instruction.md b/tasks/livewire__livewire-10626/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..68c97096867de12c7a65c4376e54d1971c9a8af6 --- /dev/null +++ b/tasks/livewire__livewire-10626/instruction.md @@ -0,0 +1,73 @@ +# Issue + +**Title:** [4.x] Preserve islands after nested Blade directives + +## Description + +Closes the compiler failure reported and diagnosed by @stebrl in #10624. + +An island can be skipped during Livewire's island-only Blade pass when earlier directives share a nested-call prefix. The compiled view keeps an `@island` without Livewire's generated token, so every request fails with `IslandCompiler::getCachedPathFromToken(): Argument #1 ($token) must be of type string, null given`. + +## User experience + +Given two ordinary directives before an island: + +```blade +@if (auth()->check()) + first +@endif + +@if (auth()->check() && request()->isMethod('get')) + second +@endif + +@island +
...
+@endisland +``` + +- **Actual:** the page deterministically returns 500 because the island token was dropped during compilation. +- **Expected:** directives before an island remain ordinary Blade and the island renders with its generated token. + +## Findings + +- Confirmed demand is narrow: #10624 is the only exact report, from one application with two affected views. The failure is nevertheless production-fatal and uses supported syntax. +- The related #10277 / #10282 fixed nested parentheses on the island directive itself; this failure happens earlier, while foreign directives are passing through the island compiler. +- Laravel's `BladeCompiler::compileStatements()` repairs an initially unbalanced regex match with a search from the start of the template. Livewire's island pass returned foreign directives unchanged, leaving earlier identical prefixes visible to that repair. Blade could then reconstruct a later directive from an earlier one, advance its forward-only replacement offset beyond the island, and silently drop the tokenized replacement. +- Livewire has already fixed the same position-vs-value lookup class in a separate compiler path in #9921. Existing Blade-comment shielding in #9838 also provides local precedent for temporarily setting source aside. + +## Directions considered + +- **Minimal:** mask the leading `@` in foreign directives during this pass. It fixes the reported case but a fixed marker can collide with authored content. +- **Maximal:** replace the hacked Blade compiler with a dedicated island parser and nested syntax tree. This removes the coupling entirely, but makes Livewire own a partial Blade lexer for escapes, comments, quotes, and malformed syntax. +- **Evaporative:** fix Laravel's global parenthesis-repair lookup upstream. Worth pursuing, but Livewire still needs a bridge across supported Laravel versions. +- **Userland:** hoist nested calls into variables/properties before the island. This works today, but is obscure, per-view, and not an appropriate framework answer. + +This PR chooses the small compatibility bridge: every non-island directive is replaced with a collision-safe, per-pass placeholder, then restored byte-for-byte before islands are extracted. Escaped directives are also preserved until Blade's real compilation pass. + +## Built as working slices + +Each commit is independently testable and evolves the same user-visible fix: + +1. **Skateboard — :** one obvious marker consumes foreign directives so Blade cannot skip the island; adds the browser regression. +2. **Bicycle — :** stores and restores each foreign directive instead of globally replacing marker text. +3. **Car — :** selects a placeholder prefix absent from the view and covers compiler fingerprints, custom directives, escaped directives, and marker-like authored content. + +## Verification + +- Reproduced current `4.x` in a real Laravel app: HTTP 500 with the null-token exception. +- Verified the final branch in the same app: HTTP 200, `count: 0` rendered, generated island token present, no internal island/directive markers leaked. +- Full unit suite: 1,408 tests / 4,017 assertions passing (13 skipped, 3 incomplete). +- Full islands browser suite: 35 tests / 192 assertions passing. +- No documentation change: this restores existing documented behavior and introduces no public API. +- No new execution surface: foreign directives remain inert source during the island pre-pass and are restored exactly for Blade's normal compiler. + +## Follow-up + +Laravel's position lookup should still be repaired upstream so other source-preserving compiler clients cannot hit the same class of failure. Livewire can remove this bridge once every supported Laravel line contains that fix. + +A separate island-parser failure remains possible when raw or verbatim content contains an unbalanced `(` or a literal `@island`: this pre-pass calls `compileStatements()` directly, before Blade stores raw/verbatim blocks. It can produce the same missing-token symptom through a different path and should be handled separately rather than folded into this targeted fix. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `db8815892bec`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10626/solution/patch.diff b/tasks/livewire__livewire-10626/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..96de10269ca20e2c6990fa91c8551210e0652ede --- /dev/null +++ b/tasks/livewire__livewire-10626/solution/patch.diff @@ -0,0 +1,225 @@ +diff --git a/src/Features/SupportIslands/BrowserTest.php b/src/Features/SupportIslands/BrowserTest.php +index b17c41ec..c4870c5e 100644 +--- a/src/Features/SupportIslands/BrowserTest.php ++++ b/src/Features/SupportIslands/BrowserTest.php +@@ -2,6 +2,7 @@ + + namespace Livewire\Features\SupportIslands; + ++use Illuminate\Support\Facades\Blade; + use Tests\BrowserTestCase; + use Livewire\Livewire; + +@@ -47,6 +48,71 @@ class BrowserTest extends BrowserTestCase + ; + } + ++ public function test_island_after_repeated_nested_blade_directives() ++ { ++ Livewire::visit([new class extends \Livewire\Component { ++ public $count = 0; ++ ++ public function render() ++ { ++ return <<<'HTML' ++
++ @if (auth()->check()) ++ first ++ @endif ++ ++ @if (auth()->check() && request()->isMethod('get')) ++ second ++ @endif ++ ++ @island ++
Count: {{ $count }}
++ @endisland ++ ++ @if (auth()->check()) ++ third ++ @endif ++ ++
[LIVEWIRE_DIRECTIVE_AT]
++
++ HTML; ++ } ++ }]) ++ ->assertSeeIn('@island', 'Count: 0') ++ ->assertSeeIn('@literal', '[LIVEWIRE_DIRECTIVE_AT]') ++ ; ++ } ++ ++ public function test_island_compilation_preserves_foreign_directives_and_marker_like_content() ++ { ++ Blade::directive('islandGreeting', fn ($expression) => '
Hello from Blade
'); ++ ++ Livewire::visit([new class extends \Livewire\Component { ++ public function render() ++ { ++ return <<<'HTML' ++
++ @islandGreeting ++ ++
[LIVEWIRE_DIRECTIVE:0]
++
@@if (true)
++ ++ @island ++
Island rendered
++
@@if (true)
++ @endisland ++
++ HTML; ++ } ++ }]) ++ ->assertSeeIn('@custom-directive', 'Hello from Blade') ++ ->assertSeeIn('@marker-like-content', '[LIVEWIRE_DIRECTIVE:0]') ++ ->assertSeeIn('@escaped-directive', '@if(true)') ++ ->assertSeeIn('@island-with-foreign-directives', 'Island rendered') ++ ->assertSeeIn('@escaped-directive-inside-island', '@if(true)') ++ ; ++ } ++ + public function test_sibling_islands() + { + Livewire::visit([new class extends \Livewire\Component { +diff --git a/src/Features/SupportIslands/Compiler/IslandCompiler.php b/src/Features/SupportIslands/Compiler/IslandCompiler.php +index d38a0da5..ce7e2661 100644 +--- a/src/Features/SupportIslands/Compiler/IslandCompiler.php ++++ b/src/Features/SupportIslands/Compiler/IslandCompiler.php +@@ -57,6 +57,8 @@ class IslandCompiler + + $result = $compiler->compileStatementsMadePublic($contents); + ++ $result = $this->restoreSetAsideDirectives($result, $compiler->setAsideDirectives); ++ + $result = $this->restoreBladeComments($result, $comments); + + for ($i=$maxNestingLevel; $i >= $currentNestingLevel; $i--) { +@@ -210,41 +212,58 @@ PHP; + }, $contents); + } + ++ protected function restoreSetAsideDirectives(string $contents, array $directives): string ++ { ++ return strtr($contents, $directives); ++ } ++ + public function getHackedBladeCompiler() + { + $instance = new class ( + app('files'), + rtrim(config('view.compiled'), '/\\') . '/livewire', + ) extends \Illuminate\View\Compilers\BladeCompiler { ++ public array $setAsideDirectives = []; ++ ++ protected string $setAsideDirectivePrefix = '[LIVEWIRE_DIRECTIVE:'; ++ + /** +- * Make this method public... ++ * Make statement compilation public and reserve a placeholder prefix ++ * that does not collide with authored view content... + */ + public function compileStatementsMadePublic($template) + { ++ while (str_contains($template, $this->setAsideDirectivePrefix)) { ++ $this->setAsideDirectivePrefix .= '_'; ++ } ++ + return $this->compileStatements($template); + } + ++ protected function setAside($directive) ++ { ++ $placeholder = $this->setAsideDirectivePrefix . count($this->setAsideDirectives) . ']'; ++ ++ $this->setAsideDirectives[$placeholder] = $directive; ++ ++ return $placeholder; ++ } ++ + /** + * Tweak this method to only process custom directives so we + * can restrict rendering solely to @island related directives... + */ + protected function compileStatement($match) + { +- if (str_contains($match[1], '@')) { +- $match[0] = isset($match[3]) ? $match[1].$match[3] : $match[1]; +- } elseif (isset($this->customDirectives[$match[1]])) { +- $match[0] = $this->callCustomDirective($match[1], Arr::get($match, 3)); +- } elseif (method_exists($this, $method = 'compile'.ucfirst($match[1]))) { +- // Don't process through built-in directive methods... +- // $match[0] = $this->$method(Arr::get($match, 3)); +- +- // Just return the original match... +- return $match[0]; +- } else { +- return $match[0]; ++ if (isset($this->customDirectives[$match[1]])) { ++ $compiled = $this->callCustomDirective($match[1], Arr::get($match, 3)); ++ ++ return isset($match[3]) ? $compiled : $compiled.$match[2]; + } + +- return isset($match[3]) ? $match[0] : $match[0].$match[2]; ++ // Blade moves forward as it replaces statements, so foreign directives ++ // must be consumed during this island-only pass and restored afterward... ++ return $this->setAside($match[0]); + } + }; + +diff --git a/src/Features/SupportIslands/UnitTest.php b/src/Features/SupportIslands/UnitTest.php +index 26474b5e..9e37a50b 100644 +--- a/src/Features/SupportIslands/UnitTest.php ++++ b/src/Features/SupportIslands/UnitTest.php +@@ -580,6 +580,50 @@ class UnitTest extends TestCase + ->assertSee('value: HELLO'); + } + ++ public function test_island_keeps_its_token_when_a_directive_above_it_has_an_unbalanced_expression() ++ { ++ $compiledPath = sys_get_temp_dir() . '/laravel-island-offset-' . uniqid(); ++ ++ config()->set('view.compiled', $compiledPath); ++ app()->forgetInstance('livewire.compiler'); ++ app()->forgetInstance('livewire.factory'); ++ ++ $compiled = IslandCompiler::compile(__FILE__, <<<'HTML' ++
++ @if (auth()->check()) ++ first ++ @endif ++ ++ @if (auth()->check() && request()->isMethod('get')) ++ second ++ @endif ++ ++ @island(name: 'counter') ++ @if (request()->isMethod('get')) ++
count: {{ $count }}
++ @endif ++ @endisland ++ ++ @if (auth()->check()) ++ third ++ @endif ++
++ HTML); ++ ++ $token = app('livewire.compiler')->cacheManager->getHash(__FILE__) . '-1'; ++ $cachedPath = IslandCompiler::getCachedPathFromToken($token); ++ ++ $this->assertStringContainsString("token: '{$token}'", $compiled); ++ $this->assertStringNotContainsString('[ENDISLAND', $compiled); ++ $this->assertStringNotContainsString('[LIVEWIRE_DIRECTIVE:', $compiled); ++ $this->assertStringContainsString("@if (auth()->check() && request()->isMethod('get'))", $compiled); ++ $this->assertFileExists($cachedPath); ++ $this->assertStringContainsString("@if (request()->isMethod('get'))", File::get($cachedPath)); ++ $this->assertStringNotContainsString('[LIVEWIRE_DIRECTIVE:', File::get($cachedPath)); ++ ++ File::deleteDirectory($compiledPath); ++ } ++ + public function test_island_tokens_are_stable_across_different_base_paths() + { + $path = '/resources/views/components/foo.blade.php'; diff --git a/tasks/livewire__livewire-10626/solution/solve.sh b/tasks/livewire__livewire-10626/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/livewire__livewire-10626/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/livewire__livewire-10626/task.toml b/tasks/livewire__livewire-10626/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..254d5d3aa5328545f822ef1906ac6b66d1ffb7a1 --- /dev/null +++ b/tasks/livewire__livewire-10626/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/livewire__livewire-10626" +description = "[4.x] Preserve islands after nested Blade directives" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "livewire", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "livewire/livewire" +ref = "db8815892bece057596cb5616ee15f6b42182bab" +reference = "https://github.com/livewire/livewire/pull/10626" +source_access = "auto" +built_at = "2026-11-16T16:09:51.558616+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:cea24ab1205cb84e7334d3543c18f890f08db9a0d0b1351be7003530a149ff28" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-08-29T14:02:22Z" +diff_format = "unified" +context_files = [ + "src/Features/SupportIslands/BrowserTest.php", + "src/Features/SupportIslands/Compiler/IslandCompiler.php", + "src/Features/SupportIslands/UnitTest.php", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 157 +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.366388+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:213aef0bee925ab7039bf836902cfd18709931f36f4c04ee402909d61749364a" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/livewire__livewire-10626/tests/capture.py b/tasks/livewire__livewire-10626/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/livewire__livewire-10626/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/livewire__livewire-10626/tests/instruction.md b/tasks/livewire__livewire-10626/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..68c97096867de12c7a65c4376e54d1971c9a8af6 --- /dev/null +++ b/tasks/livewire__livewire-10626/tests/instruction.md @@ -0,0 +1,73 @@ +# Issue + +**Title:** [4.x] Preserve islands after nested Blade directives + +## Description + +Closes the compiler failure reported and diagnosed by @stebrl in #10624. + +An island can be skipped during Livewire's island-only Blade pass when earlier directives share a nested-call prefix. The compiled view keeps an `@island` without Livewire's generated token, so every request fails with `IslandCompiler::getCachedPathFromToken(): Argument #1 ($token) must be of type string, null given`. + +## User experience + +Given two ordinary directives before an island: + +```blade +@if (auth()->check()) + first +@endif + +@if (auth()->check() && request()->isMethod('get')) + second +@endif + +@island +
...
+@endisland +``` + +- **Actual:** the page deterministically returns 500 because the island token was dropped during compilation. +- **Expected:** directives before an island remain ordinary Blade and the island renders with its generated token. + +## Findings + +- Confirmed demand is narrow: #10624 is the only exact report, from one application with two affected views. The failure is nevertheless production-fatal and uses supported syntax. +- The related #10277 / #10282 fixed nested parentheses on the island directive itself; this failure happens earlier, while foreign directives are passing through the island compiler. +- Laravel's `BladeCompiler::compileStatements()` repairs an initially unbalanced regex match with a search from the start of the template. Livewire's island pass returned foreign directives unchanged, leaving earlier identical prefixes visible to that repair. Blade could then reconstruct a later directive from an earlier one, advance its forward-only replacement offset beyond the island, and silently drop the tokenized replacement. +- Livewire has already fixed the same position-vs-value lookup class in a separate compiler path in #9921. Existing Blade-comment shielding in #9838 also provides local precedent for temporarily setting source aside. + +## Directions considered + +- **Minimal:** mask the leading `@` in foreign directives during this pass. It fixes the reported case but a fixed marker can collide with authored content. +- **Maximal:** replace the hacked Blade compiler with a dedicated island parser and nested syntax tree. This removes the coupling entirely, but makes Livewire own a partial Blade lexer for escapes, comments, quotes, and malformed syntax. +- **Evaporative:** fix Laravel's global parenthesis-repair lookup upstream. Worth pursuing, but Livewire still needs a bridge across supported Laravel versions. +- **Userland:** hoist nested calls into variables/properties before the island. This works today, but is obscure, per-view, and not an appropriate framework answer. + +This PR chooses the small compatibility bridge: every non-island directive is replaced with a collision-safe, per-pass placeholder, then restored byte-for-byte before islands are extracted. Escaped directives are also preserved until Blade's real compilation pass. + +## Built as working slices + +Each commit is independently testable and evolves the same user-visible fix: + +1. **Skateboard — :** one obvious marker consumes foreign directives so Blade cannot skip the island; adds the browser regression. +2. **Bicycle — :** stores and restores each foreign directive instead of globally replacing marker text. +3. **Car — :** selects a placeholder prefix absent from the view and covers compiler fingerprints, custom directives, escaped directives, and marker-like authored content. + +## Verification + +- Reproduced current `4.x` in a real Laravel app: HTTP 500 with the null-token exception. +- Verified the final branch in the same app: HTTP 200, `count: 0` rendered, generated island token present, no internal island/directive markers leaked. +- Full unit suite: 1,408 tests / 4,017 assertions passing (13 skipped, 3 incomplete). +- Full islands browser suite: 35 tests / 192 assertions passing. +- No documentation change: this restores existing documented behavior and introduces no public API. +- No new execution surface: foreign directives remain inert source during the island pre-pass and are restored exactly for Blade's normal compiler. + +## Follow-up + +Laravel's position lookup should still be repaired upstream so other source-preserving compiler clients cannot hit the same class of failure. Livewire can remove this bridge once every supported Laravel line contains that fix. + +A separate island-parser failure remains possible when raw or verbatim content contains an unbalanced `(` or a literal `@island`: this pre-pass calls `compileStatements()` directly, before Blade stores raw/verbatim blocks. It can produce the same missing-token symptom through a different path and should be handled separately rather than folded into this targeted fix. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `db8815892bec`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10626/tests/oracle.patch b/tasks/livewire__livewire-10626/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..96de10269ca20e2c6990fa91c8551210e0652ede --- /dev/null +++ b/tasks/livewire__livewire-10626/tests/oracle.patch @@ -0,0 +1,225 @@ +diff --git a/src/Features/SupportIslands/BrowserTest.php b/src/Features/SupportIslands/BrowserTest.php +index b17c41ec..c4870c5e 100644 +--- a/src/Features/SupportIslands/BrowserTest.php ++++ b/src/Features/SupportIslands/BrowserTest.php +@@ -2,6 +2,7 @@ + + namespace Livewire\Features\SupportIslands; + ++use Illuminate\Support\Facades\Blade; + use Tests\BrowserTestCase; + use Livewire\Livewire; + +@@ -47,6 +48,71 @@ class BrowserTest extends BrowserTestCase + ; + } + ++ public function test_island_after_repeated_nested_blade_directives() ++ { ++ Livewire::visit([new class extends \Livewire\Component { ++ public $count = 0; ++ ++ public function render() ++ { ++ return <<<'HTML' ++
++ @if (auth()->check()) ++ first ++ @endif ++ ++ @if (auth()->check() && request()->isMethod('get')) ++ second ++ @endif ++ ++ @island ++
Count: {{ $count }}
++ @endisland ++ ++ @if (auth()->check()) ++ third ++ @endif ++ ++
[LIVEWIRE_DIRECTIVE_AT]
++
++ HTML; ++ } ++ }]) ++ ->assertSeeIn('@island', 'Count: 0') ++ ->assertSeeIn('@literal', '[LIVEWIRE_DIRECTIVE_AT]') ++ ; ++ } ++ ++ public function test_island_compilation_preserves_foreign_directives_and_marker_like_content() ++ { ++ Blade::directive('islandGreeting', fn ($expression) => '
Hello from Blade
'); ++ ++ Livewire::visit([new class extends \Livewire\Component { ++ public function render() ++ { ++ return <<<'HTML' ++
++ @islandGreeting ++ ++
[LIVEWIRE_DIRECTIVE:0]
++
@@if (true)
++ ++ @island ++
Island rendered
++
@@if (true)
++ @endisland ++
++ HTML; ++ } ++ }]) ++ ->assertSeeIn('@custom-directive', 'Hello from Blade') ++ ->assertSeeIn('@marker-like-content', '[LIVEWIRE_DIRECTIVE:0]') ++ ->assertSeeIn('@escaped-directive', '@if(true)') ++ ->assertSeeIn('@island-with-foreign-directives', 'Island rendered') ++ ->assertSeeIn('@escaped-directive-inside-island', '@if(true)') ++ ; ++ } ++ + public function test_sibling_islands() + { + Livewire::visit([new class extends \Livewire\Component { +diff --git a/src/Features/SupportIslands/Compiler/IslandCompiler.php b/src/Features/SupportIslands/Compiler/IslandCompiler.php +index d38a0da5..ce7e2661 100644 +--- a/src/Features/SupportIslands/Compiler/IslandCompiler.php ++++ b/src/Features/SupportIslands/Compiler/IslandCompiler.php +@@ -57,6 +57,8 @@ class IslandCompiler + + $result = $compiler->compileStatementsMadePublic($contents); + ++ $result = $this->restoreSetAsideDirectives($result, $compiler->setAsideDirectives); ++ + $result = $this->restoreBladeComments($result, $comments); + + for ($i=$maxNestingLevel; $i >= $currentNestingLevel; $i--) { +@@ -210,41 +212,58 @@ PHP; + }, $contents); + } + ++ protected function restoreSetAsideDirectives(string $contents, array $directives): string ++ { ++ return strtr($contents, $directives); ++ } ++ + public function getHackedBladeCompiler() + { + $instance = new class ( + app('files'), + rtrim(config('view.compiled'), '/\\') . '/livewire', + ) extends \Illuminate\View\Compilers\BladeCompiler { ++ public array $setAsideDirectives = []; ++ ++ protected string $setAsideDirectivePrefix = '[LIVEWIRE_DIRECTIVE:'; ++ + /** +- * Make this method public... ++ * Make statement compilation public and reserve a placeholder prefix ++ * that does not collide with authored view content... + */ + public function compileStatementsMadePublic($template) + { ++ while (str_contains($template, $this->setAsideDirectivePrefix)) { ++ $this->setAsideDirectivePrefix .= '_'; ++ } ++ + return $this->compileStatements($template); + } + ++ protected function setAside($directive) ++ { ++ $placeholder = $this->setAsideDirectivePrefix . count($this->setAsideDirectives) . ']'; ++ ++ $this->setAsideDirectives[$placeholder] = $directive; ++ ++ return $placeholder; ++ } ++ + /** + * Tweak this method to only process custom directives so we + * can restrict rendering solely to @island related directives... + */ + protected function compileStatement($match) + { +- if (str_contains($match[1], '@')) { +- $match[0] = isset($match[3]) ? $match[1].$match[3] : $match[1]; +- } elseif (isset($this->customDirectives[$match[1]])) { +- $match[0] = $this->callCustomDirective($match[1], Arr::get($match, 3)); +- } elseif (method_exists($this, $method = 'compile'.ucfirst($match[1]))) { +- // Don't process through built-in directive methods... +- // $match[0] = $this->$method(Arr::get($match, 3)); +- +- // Just return the original match... +- return $match[0]; +- } else { +- return $match[0]; ++ if (isset($this->customDirectives[$match[1]])) { ++ $compiled = $this->callCustomDirective($match[1], Arr::get($match, 3)); ++ ++ return isset($match[3]) ? $compiled : $compiled.$match[2]; + } + +- return isset($match[3]) ? $match[0] : $match[0].$match[2]; ++ // Blade moves forward as it replaces statements, so foreign directives ++ // must be consumed during this island-only pass and restored afterward... ++ return $this->setAside($match[0]); + } + }; + +diff --git a/src/Features/SupportIslands/UnitTest.php b/src/Features/SupportIslands/UnitTest.php +index 26474b5e..9e37a50b 100644 +--- a/src/Features/SupportIslands/UnitTest.php ++++ b/src/Features/SupportIslands/UnitTest.php +@@ -580,6 +580,50 @@ class UnitTest extends TestCase + ->assertSee('value: HELLO'); + } + ++ public function test_island_keeps_its_token_when_a_directive_above_it_has_an_unbalanced_expression() ++ { ++ $compiledPath = sys_get_temp_dir() . '/laravel-island-offset-' . uniqid(); ++ ++ config()->set('view.compiled', $compiledPath); ++ app()->forgetInstance('livewire.compiler'); ++ app()->forgetInstance('livewire.factory'); ++ ++ $compiled = IslandCompiler::compile(__FILE__, <<<'HTML' ++
++ @if (auth()->check()) ++ first ++ @endif ++ ++ @if (auth()->check() && request()->isMethod('get')) ++ second ++ @endif ++ ++ @island(name: 'counter') ++ @if (request()->isMethod('get')) ++
count: {{ $count }}
++ @endif ++ @endisland ++ ++ @if (auth()->check()) ++ third ++ @endif ++
++ HTML); ++ ++ $token = app('livewire.compiler')->cacheManager->getHash(__FILE__) . '-1'; ++ $cachedPath = IslandCompiler::getCachedPathFromToken($token); ++ ++ $this->assertStringContainsString("token: '{$token}'", $compiled); ++ $this->assertStringNotContainsString('[ENDISLAND', $compiled); ++ $this->assertStringNotContainsString('[LIVEWIRE_DIRECTIVE:', $compiled); ++ $this->assertStringContainsString("@if (auth()->check() && request()->isMethod('get'))", $compiled); ++ $this->assertFileExists($cachedPath); ++ $this->assertStringContainsString("@if (request()->isMethod('get'))", File::get($cachedPath)); ++ $this->assertStringNotContainsString('[LIVEWIRE_DIRECTIVE:', File::get($cachedPath)); ++ ++ File::deleteDirectory($compiledPath); ++ } ++ + public function test_island_tokens_are_stable_across_different_base_paths() + { + $path = '/resources/views/components/foo.blade.php'; diff --git a/tasks/livewire__livewire-10626/tests/test.sh b/tasks/livewire__livewire-10626/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..653c183260861127e78a12f4cde14f5b281272a4 --- /dev/null +++ b/tasks/livewire__livewire-10626/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace db8815892bece057596cb5616ee15f6b42182bab > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/livewire__livewire-10626/tests/verifier.py b/tasks/livewire__livewire-10626/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/livewire__livewire-10626/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/livewire__livewire-10628/environment/Dockerfile b/tasks/livewire__livewire-10628/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..47b1c1103e2189b7a43895c259fcea3020af8e48 --- /dev/null +++ b/tasks/livewire__livewire-10628/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/livewire/livewire.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/livewire/livewire.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/livewire/livewire.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 5eb0926a9c9bec02e44d02962991aa4e3e0ac2bb 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 5eb0926a9c9bec02e44d02962991aa4e3e0ac2bb \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 5eb0926a9c9bec02e44d02962991aa4e3e0ac2bb \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/livewire__livewire-10628/instruction.md b/tasks/livewire__livewire-10628/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..375c53e6b553159a5a065ae4b5cbb3c2087da5e9 --- /dev/null +++ b/tasks/livewire__livewire-10628/instruction.md @@ -0,0 +1,108 @@ +# Issue + +**Title:** [4.x] Fix #[Session] non-primitives under JSON sessions + +## Description + +## Decision brief + +Fresh Laravel applications now default to JSON session serialization (). That makes `#[Session]` fail for typed non-primitive properties: a `Collection` survives Livewire updates through the snapshot synth pipeline, but after a full page refresh Laravel reads the JSON session value as a plain array and PHP rejects assigning it to `?Collection`. + +```text +Cannot assign array to property ...::$list of type ?Illuminate\Support\Collection +``` + +. Supersedes #10386. + +### Demand and product call + +- Confirmed demand is one reporter and one explicit beneficiary, with no duplicate reports or independent “me too” comments found. +- The affected surface is broader than that count: Laravel's new default exposes every new app that combines `#[Session]` with Collection, Carbon, enum, model, nested, or custom synthesized values. +- This should be fixed in core rather than documented away. The complete userland escape hatch is switching session serialization back to `php`, but that undoes Laravel's security-motivated default. Array-backed state is a safe narrow workaround, not a satisfactory `#[Session]` contract. + +### Prior decisions + +- #10252 was the original fix from @joshhanley. Review identified three constraints: don't create a careless hydration pathway, don't leak `HandleComponents` internals, and don't add cost or behavior changes to PHP-serialized sessions. +- #10276 extracted and secured `HandleSynths` specifically so features like `#[Session]` can reuse the registered synth pipeline without reaching into `HandleComponents`. +- #10630 added the missing storage-facing abstraction over `HandleSynths`: an authenticated, versioned `PersistedValueCodec`. It is now merged, and this PR builds directly on that core abstraction. +- #10386 applied that mechanism, but stored bare synth tuples. Any pre-existing session array shaped like `[data, ['s' => ...]]` could therefore be mistaken for Livewire metadata. +- Laravel solved its analogous JSON-session `ViewErrorBag` type loss with a narrowly owned codec in . This PR follows the same boundary while reusing Livewire's general synth registry. + +## Solution + +Under `session.serialization=json`, `BaseSession` delegates its value to the `PersistedValueCodec` introduced in #10630. The codec decides whether synthesis is necessary and owns recursive traversal, component context, the strict versioned envelope, authentication, and synth security checks. + +`BaseSession` now knows only that JSON sessions require storage encoding. It no longer understands synth tuples or calls `hydrate()` directly. Reads are decoded regardless of the current serializer so configuration changes do not strand encoded state; corrupt or stale values are forgotten and the property's default is preserved. + +Consequences: + +- Collections, Carbon, nested synthesized values, and registered custom synths round-trip through JSON sessions. +- JSON primitives remain raw. +- PHP-serialized sessions remain raw and pay no synth cost. +- Legacy tuple-shaped arrays remain ordinary arrays. +- Every encoded envelope is signed with the application key and scoped to its resolved session key. +- Client-authored, tampered, unsupported-version, and wrong-scope envelopes are rejected before synth hydration. +- Components intentionally using the same explicit session key can continue to share values. +- Authentic values for removed synthesizers are discarded safely instead of permanently failing every request. +- Class metadata still passes through `SecurityPolicy::validateClass()` before any synth can instantiate it. +- No `unserialize()` path is introduced. +- Forging a decodable persisted value requires `APP_KEY`, the same trust failure that permits forging Livewire snapshot checksums. + +## Progressive implementation + +Each commit is a usable stage rather than a disconnected piece: + +The prerequisite first makes the change easy in . This PR then builds the user-facing fix in usable stages: + +1. 🛹 — `BaseSession` delegates to the authenticated codec and solves the reporter's exact typed-Collection refresh failure. +2. 🛴 — proves the same path for Carbon and nested synthesized values. +3. 🚲 — proves raw PHP/primitives, explicit-key sharing, legacy tuple safety, stale-state recovery, and rejection of client-authored model envelopes under both serializers. +4. 🚗 — preserves JSON-native arrays, proves registered custom synths and Eloquent models, asserts JSON mode, and exercises add → full refresh → add. + +## Reproduction and verification + +Confirmed before the fix on the reporter's exact Livewire `v4.2.4` (`7d0bfa46`): + +1. Load the component successfully. +2. Click **Add**; `1` renders. +3. Refresh the page; Laravel returns HTTP 500 with the typed-property error above. + +Confirmed after the fix in the same Laravel 13 playground: + +1. Click **Add**; `1` renders. +2. Refresh; `1` is restored with no error. +3. Click **Add** again; `1, 2` renders. + +Automated verification: + +- Persisted-value codec: 12 tests, 19 assertions. +- SupportSession feature suite: 16 tests, 20 assertions. +- Full unit suite: 1,504 tests, 4,251 assertions; 13 existing skips and 3 existing incomplete tests. +- Focused browser regression: 1 test, 5 assertions. +- Real Laravel 13 playground: `1` after update → `1` after full refresh → `1, 2` after the next update. +- Independent review reproduced an unsigned-envelope `ModelSynth` exploit against the first design; the final signed design directly tests and rejects that path under JSON and PHP sessions. + +Session-backed Eloquent values retain normal `ModelSynth` lazy-loading semantics; this PR does not force model queries during `BaseSession::mount()`. + +## Immediate userland workaround + +Apps unable to upgrade can keep JSON-native data in the session and derive a Collection: + +```php +#[Session] +public array $listData = []; + +#[Computed] +public function list(): Collection +{ + return collect($this->listData); +} +``` + +This works for JSON-safe items but does not preserve arbitrary nested object types. + +Implementation credit: this is rebuilt from @joshhanley's original work in #10252; Josh is credited as a co-author in the first commit. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `5eb0926a9c9b`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10628/solution/patch.diff b/tasks/livewire__livewire-10628/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..7924c084302e865681fd607a18d25edee2db5219 --- /dev/null +++ b/tasks/livewire__livewire-10628/solution/patch.diff @@ -0,0 +1,608 @@ +diff --git a/src/Features/SupportSession/BaseSession.php b/src/Features/SupportSession/BaseSession.php +index 0cd16c5a..774fc5cb 100644 +--- a/src/Features/SupportSession/BaseSession.php ++++ b/src/Features/SupportSession/BaseSession.php +@@ -3,12 +3,16 @@ + namespace Livewire\Features\SupportSession; + + use Livewire\Features\SupportAttributes\Attribute as LivewireAttribute; ++use Livewire\Mechanisms\HandleSynths\CorruptPersistedValueException; ++use Livewire\Mechanisms\HandleSynths\PersistedValueCodec; + use Illuminate\Support\Facades\Session; + use Attribute; + + #[Attribute(Attribute::TARGET_PROPERTY)] + class BaseSession extends LivewireAttribute + { ++ protected $codec; ++ + function __construct( + protected $key = null, + ) {} +@@ -17,9 +21,23 @@ class BaseSession extends LivewireAttribute + { + if (! $this->exists()) return; + +- $fromSession = $this->read(); ++ try { ++ $fromSession = $this->read(); ++ } catch (CorruptPersistedValueException) { ++ Session::forget($this->key()); ++ ++ return; ++ } + +- $this->setValue($fromSession); ++ // A stored value can become unassignable after it was persisted: its ++ // type no longer matches the property (\TypeError), or it's a scalar ++ // backing a since-removed enum case (\ValueError from Enum::from()). ++ // Either way the stale value is forgotten and the default preserved. ++ try { ++ $this->setValue($fromSession); ++ } catch (\TypeError|\ValueError) { ++ Session::forget($this->key()); ++ } + } + + public function dehydrate($context) +@@ -34,12 +52,43 @@ class BaseSession extends LivewireAttribute + + protected function read() + { +- return Session::get($this->key()); ++ // Always decode so changing session serializers doesn't strand values ++ // that Livewire encoded before the configuration changed. ++ $key = $this->key(); ++ ++ return $this->codec()->decodeFromStorage( ++ Session::get($key), ++ $this->component, ++ $this->getName(), ++ $key, ++ ); + } + + protected function write() + { +- Session::put($this->key(), $this->getValue()); ++ $value = $this->getValue(); ++ $key = $this->key(); ++ ++ if ($this->sessionIsJsonSerialized()) { ++ $value = $this->codec()->encodeForStorage( ++ $value, ++ $this->component, ++ $this->getName(), ++ $key, ++ ); ++ } ++ ++ Session::put($key, $value); ++ } ++ ++ protected function sessionIsJsonSerialized() ++ { ++ return config('session.serialization', 'php') === 'json'; ++ } ++ ++ protected function codec() ++ { ++ return $this->codec ??= app(PersistedValueCodec::class); + } + + protected function key() +diff --git a/src/Features/SupportSession/JsonSerializationBrowserTest.php b/src/Features/SupportSession/JsonSerializationBrowserTest.php +new file mode 100644 +index 00000000..64bdb9bf +--- /dev/null ++++ b/src/Features/SupportSession/JsonSerializationBrowserTest.php +@@ -0,0 +1,56 @@ ++ 'json']); ++ }; ++ } ++ ++ public function test_collection_properties_survive_a_full_page_refresh() ++ { ++ Livewire::visit(new class extends Component { ++ #[Session] ++ public ?Collection $list = null; ++ ++ public function mount(): void ++ { ++ $this->list ??= collect(); ++ } ++ ++ public function add(): void ++ { ++ $this->list->push($this->list->count() + 1); ++ } ++ ++ public function render() ++ { ++ return <<<'HTML' ++
++ {{ config('session.serialization') }} ++ ++ {{ $list->implode(', ') }} ++
++ HTML; ++ } ++ }) ++ ->assertSeeIn('@serialization', 'json') ++ ->assertSeeIn('@list', '') ++ ->waitForLivewire()->click('@button') ++ ->assertSeeIn('@list', '1') ++ ->refresh() ++ ->assertSeeIn('@list', '1') ++ ->waitForLivewire()->click('@button') ++ ->assertSeeIn('@list', '1, 2'); ++ } ++} +diff --git a/src/Features/SupportSession/UnitTest.php b/src/Features/SupportSession/UnitTest.php +index 243f6895..e027d058 100644 +--- a/src/Features/SupportSession/UnitTest.php ++++ b/src/Features/SupportSession/UnitTest.php +@@ -2,11 +2,19 @@ + + namespace Livewire\Features\SupportSession; + ++use Illuminate\Database\Eloquent\Model; ++use Illuminate\Support\Carbon; ++use Illuminate\Support\Collection; + use Illuminate\Support\Facades\Session as FacadesSession; + use Livewire\Attributes\Session; ++use Livewire\Component; ++use Livewire\Mechanisms\HandleComponents\Synthesizers\Synth; ++use Livewire\Mechanisms\HandleSynths\HandleSynths; ++use Livewire\Mechanisms\HandleSynths\PersistedValueCodec; + use Tests\TestCase; + use Livewire\Livewire; + use Tests\TestComponent; ++use Sushi\Sushi; + + class UnitTest extends TestCase + { +@@ -43,4 +51,428 @@ class UnitTest extends TestCase + + $this->assertTrue(FacadesSession::has('baz.2')); + } ++ ++ public function test_collection_properties_survive_json_session_serialization() ++ { ++ config(['session.serialization' => 'json']); ++ ++ app('session')->forgetDrivers(); ++ ++ Livewire::test(ComponentWithSessionCollection::class) ++ ->call('add'); ++ ++ session()->save(); ++ session()->start(); ++ ++ Livewire::test(ComponentWithSessionCollection::class) ++ ->assertSet('list', fn ($list) => $list instanceof Collection && $list->all() === [1]); ++ } ++ ++ public function test_synthesized_properties_survive_json_session_serialization() ++ { ++ config(['session.serialization' => 'json']); ++ ++ app('session')->forgetDrivers(); ++ ++ $date = Carbon::parse('2026-01-15 10:00:00'); ++ ++ Livewire::test(ComponentWithSynthesizedSessionProperties::class) ++ ->set('when', $date) ++ ->set('nested', ['list' => collect([1, 2]), 'when' => $date]); ++ ++ session()->save(); ++ session()->start(); ++ ++ Livewire::test(ComponentWithSynthesizedSessionProperties::class) ++ ->assertSet('when', fn ($when) => $when instanceof Carbon && $when->equalTo($date)) ++ ->assertSet('nested', fn ($nested) => $nested['list'] instanceof Collection ++ && $nested['list']->all() === [1, 2] ++ && $nested['when'] instanceof Carbon ++ && $nested['when']->equalTo($date)); ++ } ++ ++ public function test_custom_synthesized_properties_survive_json_session_serialization() ++ { ++ config(['session.serialization' => 'json']); ++ ++ app('session')->forgetDrivers(); ++ app(HandleSynths::class)->registerSynth(CustomSessionValueSynth::class); ++ ++ Livewire::test(ComponentWithCustomSynthesizedSessionProperty::class); ++ ++ session()->save(); ++ session()->start(); ++ ++ Livewire::test(ComponentWithCustomSynthesizedSessionProperty::class) ++ ->assertSet('value', fn ($value) => $value instanceof CustomSessionValue && $value->value === 'persisted'); ++ } ++ ++ public function test_model_properties_survive_json_session_serialization() ++ { ++ config(['session.serialization' => 'json']); ++ ++ app('session')->forgetDrivers(); ++ ++ Livewire::test(ComponentWithSessionModel::class) ++ ->assertSet('article', fn ($article) => $article instanceof SessionArticle && $article->title === 'First'); ++ ++ session()->save(); ++ session()->start(); ++ ++ Livewire::test(ComponentWithSessionModel::class) ++ ->assertSet('article', fn ($article) => $article instanceof SessionArticle && $article->title === 'First'); ++ } ++ ++ public function test_php_sessions_continue_to_store_values_raw() ++ { ++ config(['session.serialization' => 'php']); ++ ++ app('session')->forgetDrivers(); ++ ++ Livewire::test(ComponentWithSessionCollection::class) ++ ->call('add'); ++ ++ $stored = session('collection'); ++ ++ $this->assertInstanceOf(Collection::class, $stored); ++ $this->assertSame([1], $stored->all()); ++ } ++ ++ public function test_json_sessions_continue_to_store_primitive_values_raw() ++ { ++ config(['session.serialization' => 'json']); ++ ++ app('session')->forgetDrivers(); ++ ++ Livewire::test(ComponentWithPrimitiveSessionProperty::class) ++ ->set('count', 1); ++ ++ $this->assertSame(1, session('primitive')); ++ $this->assertSame(['search' => '', 'tags' => [1, 2]], session('json-native')); ++ } ++ ++ public function test_legacy_tuple_shaped_arrays_are_not_treated_as_synthetic_values() ++ { ++ $tuple = [['one', 'two'], ['s' => 'clctn', 'class' => Collection::class]]; ++ ++ FacadesSession::put('legacy-tuple', $tuple); ++ ++ Livewire::test(ComponentWithRawSessionArray::class) ++ ->assertSet('value', $tuple); ++ } ++ ++ public function test_session_envelopes_are_decoded_even_after_switching_to_php_serialization() ++ { ++ config(['session.serialization' => 'json']); ++ ++ app('session')->forgetDrivers(); ++ ++ Livewire::test(ComponentWithSessionCollection::class) ++ ->call('add'); ++ ++ config(['session.serialization' => 'php']); ++ ++ Livewire::test(ComponentWithSessionCollection::class) ++ ->assertSet('list', fn ($list) => $list instanceof Collection && $list->all() === [1]); ++ } ++ ++ public function test_client_authored_synth_envelopes_are_discarded_in_json_sessions() ++ { ++ $this->assertClientAuthoredSynthEnvelopeIsDiscarded('json'); ++ } ++ ++ public function test_client_authored_synth_envelopes_are_discarded_in_php_sessions() ++ { ++ $this->assertClientAuthoredSynthEnvelopeIsDiscarded('php'); ++ } ++ ++ public function test_unreadable_persisted_envelopes_are_discarded() ++ { ++ config(['session.serialization' => 'json']); ++ ++ app('session')->forgetDrivers(); ++ ++ Livewire::test(ComponentWithSessionCollection::class) ++ ->call('add'); ++ ++ $stored = session('collection'); ++ $stored[PersistedValueCodec::KEY]['version']++; ++ ++ FacadesSession::put('collection', $stored); ++ ++ Livewire::test(ComponentWithSessionCollection::class) ++ ->assertSet('list', fn ($list) => $list instanceof Collection && $list->isEmpty()); ++ } ++ ++ public function test_components_can_share_an_explicit_session_key() ++ { ++ config(['session.serialization' => 'json']); ++ ++ app('session')->forgetDrivers(); ++ ++ Livewire::test(ComponentWithSessionCollection::class) ++ ->call('add'); ++ ++ session()->save(); ++ session()->start(); ++ ++ Livewire::test(ComponentReadingSharedSessionCollection::class) ++ ->assertSet('items', fn ($items) => $items instanceof Collection && $items->all() === [1]); ++ } ++ ++ public function test_values_for_synths_that_are_no_longer_registered_are_discarded() ++ { ++ config(['session.serialization' => 'json']); ++ ++ app('session')->forgetDrivers(); ++ ++ $encoded = app(PersistedValueCodec::class)->encodeForStorage( ++ new \Illuminate\Foundation\Auth\User, ++ new TestComponent, ++ 'value', ++ 'dangerous-value', ++ ); ++ ++ FacadesSession::put('dangerous-value', $encoded); ++ ++ app()->instance( ++ \Livewire\Mechanisms\HandleSynths\HandleSynths::class, ++ new \Livewire\Mechanisms\HandleSynths\HandleSynths, ++ ); ++ ++ Livewire::test(ComponentWithDangerousSessionProperty::class) ++ ->assertSet('value', 'safe'); ++ } ++ ++ public function test_json_arrays_left_by_older_versions_are_discarded_from_typed_properties() ++ { ++ config(['session.serialization' => 'json']); ++ ++ app('session')->forgetDrivers(); ++ FacadesSession::put('stale-collection', [1, 2]); ++ ++ Livewire::test(ComponentWithStaleSessionCollection::class) ++ ->assertSet('list', null); ++ } ++ ++ public function test_stale_enum_backing_values_are_discarded_from_typed_properties() ++ { ++ config(['session.serialization' => 'json']); ++ ++ app('session')->forgetDrivers(); ++ ++ // A scalar backing an enum case that no longer exists (a removed or ++ // renamed case, or a value written before the enum changed). Coercing ++ // it throws a ValueError that must be recovered from, not surfaced. ++ FacadesSession::put('stale-enum', 'archived'); ++ ++ Livewire::test(ComponentWithSessionEnum::class) ++ ->assertSet('status', null); ++ } ++ ++ protected function assertClientAuthoredSynthEnvelopeIsDiscarded($serialization) ++ { ++ config(['session.serialization' => $serialization]); ++ ++ app('session')->forgetDrivers(); ++ ++ Livewire::test(ComponentWithDangerousSessionProperty::class) ++ ->set('value', [ ++ PersistedValueCodec::KEY => [ ++ 'version' => PersistedValueCodec::VERSION, ++ 'value' => [null, [ ++ 's' => 'mdl', ++ 'class' => \Illuminate\Foundation\Auth\User::class, ++ 'key' => 1, ++ ]], ++ ], ++ ]); ++ ++ session()->save(); ++ session()->start(); ++ ++ Livewire::test(ComponentWithDangerousSessionProperty::class) ++ ->assertSet('value', 'safe'); ++ } ++} ++ ++class ComponentWithSessionCollection extends Component ++{ ++ #[Session(key: 'collection')] ++ public ?Collection $list = null; ++ ++ public function mount(): void ++ { ++ $this->list ??= collect(); ++ } ++ ++ public function add(): void ++ { ++ $this->list->push($this->list->count() + 1); ++ } ++ ++ public function render() ++ { ++ return '
{{ $list->implode(", ") }}
'; ++ } ++} ++ ++class ComponentReadingSharedSessionCollection extends Component ++{ ++ #[Session(key: 'collection')] ++ public ?Collection $items = null; ++ ++ public function mount(): void ++ { ++ $this->items ??= collect(); ++ } ++ ++ public function render() ++ { ++ return '
'; ++ } ++} ++ ++class ComponentWithSynthesizedSessionProperties extends Component ++{ ++ #[Session] ++ public ?Carbon $when = null; ++ ++ #[Session] ++ public array $nested = []; ++ ++ public function render() ++ { ++ return '
'; ++ } ++} ++ ++class ComponentWithCustomSynthesizedSessionProperty extends Component ++{ ++ #[Session] ++ public ?CustomSessionValue $value = null; ++ ++ public function mount() ++ { ++ $this->value ??= new CustomSessionValue('persisted'); ++ } ++ ++ public function render() ++ { ++ return '
'; ++ } ++} ++ ++class ComponentWithSessionModel extends Component ++{ ++ #[Session(key: 'article')] ++ public ?SessionArticle $article = null; ++ ++ public function mount() ++ { ++ $this->article ??= SessionArticle::first(); ++ } ++ ++ public function render() ++ { ++ return '
'; ++ } ++} ++ ++class SessionArticle extends Model ++{ ++ use Sushi; ++ ++ protected $rows = [ ++ ['title' => 'First'], ++ ]; ++} ++ ++class CustomSessionValue ++{ ++ public function __construct(public string $value) {} ++} ++ ++class CustomSessionValueSynth extends Synth ++{ ++ public static $key = 'session-value'; ++ ++ public static function match($target) ++ { ++ return $target instanceof CustomSessionValue; ++ } ++ ++ public function dehydrate($target) ++ { ++ return [$target->value, []]; ++ } ++ ++ public function hydrate($value) ++ { ++ return new CustomSessionValue($value); ++ } ++} ++ ++class ComponentWithPrimitiveSessionProperty extends Component ++{ ++ #[Session(key: 'primitive')] ++ public int $count = 0; ++ ++ #[Session(key: 'json-native')] ++ public array $filters = ['search' => '', 'tags' => [1, 2]]; ++ ++ public function render() ++ { ++ return '
'; ++ } ++} ++ ++class ComponentWithRawSessionArray extends Component ++{ ++ #[Session(key: 'legacy-tuple')] ++ public array $value = []; ++ ++ public function render() ++ { ++ return '
'; ++ } ++} ++ ++class ComponentWithDangerousSessionProperty extends Component ++{ ++ #[Session(key: 'dangerous-value')] ++ public $value = 'safe'; ++ ++ public function render() ++ { ++ return '
'; ++ } ++} ++ ++class ComponentWithStaleSessionCollection extends Component ++{ ++ #[Session(key: 'stale-collection')] ++ public ?Collection $list = null; ++ ++ public function render() ++ { ++ return '
'; ++ } ++} ++ ++enum SessionStatus: string ++{ ++ case Draft = 'draft'; ++ case Published = 'published'; ++} ++ ++class ComponentWithSessionEnum extends Component ++{ ++ #[Session(key: 'stale-enum')] ++ public ?SessionStatus $status = null; ++ ++ public function render() ++ { ++ return '
'; ++ } + } diff --git a/tasks/livewire__livewire-10628/solution/solve.sh b/tasks/livewire__livewire-10628/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/livewire__livewire-10628/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/livewire__livewire-10628/task.toml b/tasks/livewire__livewire-10628/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..3294b511867ace97b926af490703081c5684d2ac --- /dev/null +++ b/tasks/livewire__livewire-10628/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/livewire__livewire-10628" +description = "[4.x] Fix #[Session] non-primitives under JSON sessions" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "livewire", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "livewire/livewire" +ref = "5eb0926a9c9bec02e44d02962991aa4e3e0ac2bb" +reference = "https://github.com/livewire/livewire/pull/10628" +source_access = "auto" +built_at = "2026-11-16T16:09:51.536200+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:65324105677c0ba95133b1d031c3dd9f56e2dec59f97acbba0e5d6d839049390" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-08-30T12:22:19Z" +diff_format = "unified" +context_files = [ + "src/Features/SupportSession/BaseSession.php", + "src/Features/SupportSession/JsonSerializationBrowserTest.php", + "src/Features/SupportSession/UnitTest.php", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 545 +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.366870+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:3f1e3ad1d08e8be0ccdd7b3949a3344a447196e075b10ed056a3c65f87c74f0b" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/livewire__livewire-10628/tests/capture.py b/tasks/livewire__livewire-10628/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/livewire__livewire-10628/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/livewire__livewire-10628/tests/instruction.md b/tasks/livewire__livewire-10628/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..375c53e6b553159a5a065ae4b5cbb3c2087da5e9 --- /dev/null +++ b/tasks/livewire__livewire-10628/tests/instruction.md @@ -0,0 +1,108 @@ +# Issue + +**Title:** [4.x] Fix #[Session] non-primitives under JSON sessions + +## Description + +## Decision brief + +Fresh Laravel applications now default to JSON session serialization (). That makes `#[Session]` fail for typed non-primitive properties: a `Collection` survives Livewire updates through the snapshot synth pipeline, but after a full page refresh Laravel reads the JSON session value as a plain array and PHP rejects assigning it to `?Collection`. + +```text +Cannot assign array to property ...::$list of type ?Illuminate\Support\Collection +``` + +. Supersedes #10386. + +### Demand and product call + +- Confirmed demand is one reporter and one explicit beneficiary, with no duplicate reports or independent “me too” comments found. +- The affected surface is broader than that count: Laravel's new default exposes every new app that combines `#[Session]` with Collection, Carbon, enum, model, nested, or custom synthesized values. +- This should be fixed in core rather than documented away. The complete userland escape hatch is switching session serialization back to `php`, but that undoes Laravel's security-motivated default. Array-backed state is a safe narrow workaround, not a satisfactory `#[Session]` contract. + +### Prior decisions + +- #10252 was the original fix from @joshhanley. Review identified three constraints: don't create a careless hydration pathway, don't leak `HandleComponents` internals, and don't add cost or behavior changes to PHP-serialized sessions. +- #10276 extracted and secured `HandleSynths` specifically so features like `#[Session]` can reuse the registered synth pipeline without reaching into `HandleComponents`. +- #10630 added the missing storage-facing abstraction over `HandleSynths`: an authenticated, versioned `PersistedValueCodec`. It is now merged, and this PR builds directly on that core abstraction. +- #10386 applied that mechanism, but stored bare synth tuples. Any pre-existing session array shaped like `[data, ['s' => ...]]` could therefore be mistaken for Livewire metadata. +- Laravel solved its analogous JSON-session `ViewErrorBag` type loss with a narrowly owned codec in . This PR follows the same boundary while reusing Livewire's general synth registry. + +## Solution + +Under `session.serialization=json`, `BaseSession` delegates its value to the `PersistedValueCodec` introduced in #10630. The codec decides whether synthesis is necessary and owns recursive traversal, component context, the strict versioned envelope, authentication, and synth security checks. + +`BaseSession` now knows only that JSON sessions require storage encoding. It no longer understands synth tuples or calls `hydrate()` directly. Reads are decoded regardless of the current serializer so configuration changes do not strand encoded state; corrupt or stale values are forgotten and the property's default is preserved. + +Consequences: + +- Collections, Carbon, nested synthesized values, and registered custom synths round-trip through JSON sessions. +- JSON primitives remain raw. +- PHP-serialized sessions remain raw and pay no synth cost. +- Legacy tuple-shaped arrays remain ordinary arrays. +- Every encoded envelope is signed with the application key and scoped to its resolved session key. +- Client-authored, tampered, unsupported-version, and wrong-scope envelopes are rejected before synth hydration. +- Components intentionally using the same explicit session key can continue to share values. +- Authentic values for removed synthesizers are discarded safely instead of permanently failing every request. +- Class metadata still passes through `SecurityPolicy::validateClass()` before any synth can instantiate it. +- No `unserialize()` path is introduced. +- Forging a decodable persisted value requires `APP_KEY`, the same trust failure that permits forging Livewire snapshot checksums. + +## Progressive implementation + +Each commit is a usable stage rather than a disconnected piece: + +The prerequisite first makes the change easy in . This PR then builds the user-facing fix in usable stages: + +1. 🛹 — `BaseSession` delegates to the authenticated codec and solves the reporter's exact typed-Collection refresh failure. +2. 🛴 — proves the same path for Carbon and nested synthesized values. +3. 🚲 — proves raw PHP/primitives, explicit-key sharing, legacy tuple safety, stale-state recovery, and rejection of client-authored model envelopes under both serializers. +4. 🚗 — preserves JSON-native arrays, proves registered custom synths and Eloquent models, asserts JSON mode, and exercises add → full refresh → add. + +## Reproduction and verification + +Confirmed before the fix on the reporter's exact Livewire `v4.2.4` (`7d0bfa46`): + +1. Load the component successfully. +2. Click **Add**; `1` renders. +3. Refresh the page; Laravel returns HTTP 500 with the typed-property error above. + +Confirmed after the fix in the same Laravel 13 playground: + +1. Click **Add**; `1` renders. +2. Refresh; `1` is restored with no error. +3. Click **Add** again; `1, 2` renders. + +Automated verification: + +- Persisted-value codec: 12 tests, 19 assertions. +- SupportSession feature suite: 16 tests, 20 assertions. +- Full unit suite: 1,504 tests, 4,251 assertions; 13 existing skips and 3 existing incomplete tests. +- Focused browser regression: 1 test, 5 assertions. +- Real Laravel 13 playground: `1` after update → `1` after full refresh → `1, 2` after the next update. +- Independent review reproduced an unsigned-envelope `ModelSynth` exploit against the first design; the final signed design directly tests and rejects that path under JSON and PHP sessions. + +Session-backed Eloquent values retain normal `ModelSynth` lazy-loading semantics; this PR does not force model queries during `BaseSession::mount()`. + +## Immediate userland workaround + +Apps unable to upgrade can keep JSON-native data in the session and derive a Collection: + +```php +#[Session] +public array $listData = []; + +#[Computed] +public function list(): Collection +{ + return collect($this->listData); +} +``` + +This works for JSON-safe items but does not preserve arbitrary nested object types. + +Implementation credit: this is rebuilt from @joshhanley's original work in #10252; Josh is credited as a co-author in the first commit. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `5eb0926a9c9b`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10628/tests/oracle.patch b/tasks/livewire__livewire-10628/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..7924c084302e865681fd607a18d25edee2db5219 --- /dev/null +++ b/tasks/livewire__livewire-10628/tests/oracle.patch @@ -0,0 +1,608 @@ +diff --git a/src/Features/SupportSession/BaseSession.php b/src/Features/SupportSession/BaseSession.php +index 0cd16c5a..774fc5cb 100644 +--- a/src/Features/SupportSession/BaseSession.php ++++ b/src/Features/SupportSession/BaseSession.php +@@ -3,12 +3,16 @@ + namespace Livewire\Features\SupportSession; + + use Livewire\Features\SupportAttributes\Attribute as LivewireAttribute; ++use Livewire\Mechanisms\HandleSynths\CorruptPersistedValueException; ++use Livewire\Mechanisms\HandleSynths\PersistedValueCodec; + use Illuminate\Support\Facades\Session; + use Attribute; + + #[Attribute(Attribute::TARGET_PROPERTY)] + class BaseSession extends LivewireAttribute + { ++ protected $codec; ++ + function __construct( + protected $key = null, + ) {} +@@ -17,9 +21,23 @@ class BaseSession extends LivewireAttribute + { + if (! $this->exists()) return; + +- $fromSession = $this->read(); ++ try { ++ $fromSession = $this->read(); ++ } catch (CorruptPersistedValueException) { ++ Session::forget($this->key()); ++ ++ return; ++ } + +- $this->setValue($fromSession); ++ // A stored value can become unassignable after it was persisted: its ++ // type no longer matches the property (\TypeError), or it's a scalar ++ // backing a since-removed enum case (\ValueError from Enum::from()). ++ // Either way the stale value is forgotten and the default preserved. ++ try { ++ $this->setValue($fromSession); ++ } catch (\TypeError|\ValueError) { ++ Session::forget($this->key()); ++ } + } + + public function dehydrate($context) +@@ -34,12 +52,43 @@ class BaseSession extends LivewireAttribute + + protected function read() + { +- return Session::get($this->key()); ++ // Always decode so changing session serializers doesn't strand values ++ // that Livewire encoded before the configuration changed. ++ $key = $this->key(); ++ ++ return $this->codec()->decodeFromStorage( ++ Session::get($key), ++ $this->component, ++ $this->getName(), ++ $key, ++ ); + } + + protected function write() + { +- Session::put($this->key(), $this->getValue()); ++ $value = $this->getValue(); ++ $key = $this->key(); ++ ++ if ($this->sessionIsJsonSerialized()) { ++ $value = $this->codec()->encodeForStorage( ++ $value, ++ $this->component, ++ $this->getName(), ++ $key, ++ ); ++ } ++ ++ Session::put($key, $value); ++ } ++ ++ protected function sessionIsJsonSerialized() ++ { ++ return config('session.serialization', 'php') === 'json'; ++ } ++ ++ protected function codec() ++ { ++ return $this->codec ??= app(PersistedValueCodec::class); + } + + protected function key() +diff --git a/src/Features/SupportSession/JsonSerializationBrowserTest.php b/src/Features/SupportSession/JsonSerializationBrowserTest.php +new file mode 100644 +index 00000000..64bdb9bf +--- /dev/null ++++ b/src/Features/SupportSession/JsonSerializationBrowserTest.php +@@ -0,0 +1,56 @@ ++ 'json']); ++ }; ++ } ++ ++ public function test_collection_properties_survive_a_full_page_refresh() ++ { ++ Livewire::visit(new class extends Component { ++ #[Session] ++ public ?Collection $list = null; ++ ++ public function mount(): void ++ { ++ $this->list ??= collect(); ++ } ++ ++ public function add(): void ++ { ++ $this->list->push($this->list->count() + 1); ++ } ++ ++ public function render() ++ { ++ return <<<'HTML' ++
++ {{ config('session.serialization') }} ++ ++ {{ $list->implode(', ') }} ++
++ HTML; ++ } ++ }) ++ ->assertSeeIn('@serialization', 'json') ++ ->assertSeeIn('@list', '') ++ ->waitForLivewire()->click('@button') ++ ->assertSeeIn('@list', '1') ++ ->refresh() ++ ->assertSeeIn('@list', '1') ++ ->waitForLivewire()->click('@button') ++ ->assertSeeIn('@list', '1, 2'); ++ } ++} +diff --git a/src/Features/SupportSession/UnitTest.php b/src/Features/SupportSession/UnitTest.php +index 243f6895..e027d058 100644 +--- a/src/Features/SupportSession/UnitTest.php ++++ b/src/Features/SupportSession/UnitTest.php +@@ -2,11 +2,19 @@ + + namespace Livewire\Features\SupportSession; + ++use Illuminate\Database\Eloquent\Model; ++use Illuminate\Support\Carbon; ++use Illuminate\Support\Collection; + use Illuminate\Support\Facades\Session as FacadesSession; + use Livewire\Attributes\Session; ++use Livewire\Component; ++use Livewire\Mechanisms\HandleComponents\Synthesizers\Synth; ++use Livewire\Mechanisms\HandleSynths\HandleSynths; ++use Livewire\Mechanisms\HandleSynths\PersistedValueCodec; + use Tests\TestCase; + use Livewire\Livewire; + use Tests\TestComponent; ++use Sushi\Sushi; + + class UnitTest extends TestCase + { +@@ -43,4 +51,428 @@ class UnitTest extends TestCase + + $this->assertTrue(FacadesSession::has('baz.2')); + } ++ ++ public function test_collection_properties_survive_json_session_serialization() ++ { ++ config(['session.serialization' => 'json']); ++ ++ app('session')->forgetDrivers(); ++ ++ Livewire::test(ComponentWithSessionCollection::class) ++ ->call('add'); ++ ++ session()->save(); ++ session()->start(); ++ ++ Livewire::test(ComponentWithSessionCollection::class) ++ ->assertSet('list', fn ($list) => $list instanceof Collection && $list->all() === [1]); ++ } ++ ++ public function test_synthesized_properties_survive_json_session_serialization() ++ { ++ config(['session.serialization' => 'json']); ++ ++ app('session')->forgetDrivers(); ++ ++ $date = Carbon::parse('2026-01-15 10:00:00'); ++ ++ Livewire::test(ComponentWithSynthesizedSessionProperties::class) ++ ->set('when', $date) ++ ->set('nested', ['list' => collect([1, 2]), 'when' => $date]); ++ ++ session()->save(); ++ session()->start(); ++ ++ Livewire::test(ComponentWithSynthesizedSessionProperties::class) ++ ->assertSet('when', fn ($when) => $when instanceof Carbon && $when->equalTo($date)) ++ ->assertSet('nested', fn ($nested) => $nested['list'] instanceof Collection ++ && $nested['list']->all() === [1, 2] ++ && $nested['when'] instanceof Carbon ++ && $nested['when']->equalTo($date)); ++ } ++ ++ public function test_custom_synthesized_properties_survive_json_session_serialization() ++ { ++ config(['session.serialization' => 'json']); ++ ++ app('session')->forgetDrivers(); ++ app(HandleSynths::class)->registerSynth(CustomSessionValueSynth::class); ++ ++ Livewire::test(ComponentWithCustomSynthesizedSessionProperty::class); ++ ++ session()->save(); ++ session()->start(); ++ ++ Livewire::test(ComponentWithCustomSynthesizedSessionProperty::class) ++ ->assertSet('value', fn ($value) => $value instanceof CustomSessionValue && $value->value === 'persisted'); ++ } ++ ++ public function test_model_properties_survive_json_session_serialization() ++ { ++ config(['session.serialization' => 'json']); ++ ++ app('session')->forgetDrivers(); ++ ++ Livewire::test(ComponentWithSessionModel::class) ++ ->assertSet('article', fn ($article) => $article instanceof SessionArticle && $article->title === 'First'); ++ ++ session()->save(); ++ session()->start(); ++ ++ Livewire::test(ComponentWithSessionModel::class) ++ ->assertSet('article', fn ($article) => $article instanceof SessionArticle && $article->title === 'First'); ++ } ++ ++ public function test_php_sessions_continue_to_store_values_raw() ++ { ++ config(['session.serialization' => 'php']); ++ ++ app('session')->forgetDrivers(); ++ ++ Livewire::test(ComponentWithSessionCollection::class) ++ ->call('add'); ++ ++ $stored = session('collection'); ++ ++ $this->assertInstanceOf(Collection::class, $stored); ++ $this->assertSame([1], $stored->all()); ++ } ++ ++ public function test_json_sessions_continue_to_store_primitive_values_raw() ++ { ++ config(['session.serialization' => 'json']); ++ ++ app('session')->forgetDrivers(); ++ ++ Livewire::test(ComponentWithPrimitiveSessionProperty::class) ++ ->set('count', 1); ++ ++ $this->assertSame(1, session('primitive')); ++ $this->assertSame(['search' => '', 'tags' => [1, 2]], session('json-native')); ++ } ++ ++ public function test_legacy_tuple_shaped_arrays_are_not_treated_as_synthetic_values() ++ { ++ $tuple = [['one', 'two'], ['s' => 'clctn', 'class' => Collection::class]]; ++ ++ FacadesSession::put('legacy-tuple', $tuple); ++ ++ Livewire::test(ComponentWithRawSessionArray::class) ++ ->assertSet('value', $tuple); ++ } ++ ++ public function test_session_envelopes_are_decoded_even_after_switching_to_php_serialization() ++ { ++ config(['session.serialization' => 'json']); ++ ++ app('session')->forgetDrivers(); ++ ++ Livewire::test(ComponentWithSessionCollection::class) ++ ->call('add'); ++ ++ config(['session.serialization' => 'php']); ++ ++ Livewire::test(ComponentWithSessionCollection::class) ++ ->assertSet('list', fn ($list) => $list instanceof Collection && $list->all() === [1]); ++ } ++ ++ public function test_client_authored_synth_envelopes_are_discarded_in_json_sessions() ++ { ++ $this->assertClientAuthoredSynthEnvelopeIsDiscarded('json'); ++ } ++ ++ public function test_client_authored_synth_envelopes_are_discarded_in_php_sessions() ++ { ++ $this->assertClientAuthoredSynthEnvelopeIsDiscarded('php'); ++ } ++ ++ public function test_unreadable_persisted_envelopes_are_discarded() ++ { ++ config(['session.serialization' => 'json']); ++ ++ app('session')->forgetDrivers(); ++ ++ Livewire::test(ComponentWithSessionCollection::class) ++ ->call('add'); ++ ++ $stored = session('collection'); ++ $stored[PersistedValueCodec::KEY]['version']++; ++ ++ FacadesSession::put('collection', $stored); ++ ++ Livewire::test(ComponentWithSessionCollection::class) ++ ->assertSet('list', fn ($list) => $list instanceof Collection && $list->isEmpty()); ++ } ++ ++ public function test_components_can_share_an_explicit_session_key() ++ { ++ config(['session.serialization' => 'json']); ++ ++ app('session')->forgetDrivers(); ++ ++ Livewire::test(ComponentWithSessionCollection::class) ++ ->call('add'); ++ ++ session()->save(); ++ session()->start(); ++ ++ Livewire::test(ComponentReadingSharedSessionCollection::class) ++ ->assertSet('items', fn ($items) => $items instanceof Collection && $items->all() === [1]); ++ } ++ ++ public function test_values_for_synths_that_are_no_longer_registered_are_discarded() ++ { ++ config(['session.serialization' => 'json']); ++ ++ app('session')->forgetDrivers(); ++ ++ $encoded = app(PersistedValueCodec::class)->encodeForStorage( ++ new \Illuminate\Foundation\Auth\User, ++ new TestComponent, ++ 'value', ++ 'dangerous-value', ++ ); ++ ++ FacadesSession::put('dangerous-value', $encoded); ++ ++ app()->instance( ++ \Livewire\Mechanisms\HandleSynths\HandleSynths::class, ++ new \Livewire\Mechanisms\HandleSynths\HandleSynths, ++ ); ++ ++ Livewire::test(ComponentWithDangerousSessionProperty::class) ++ ->assertSet('value', 'safe'); ++ } ++ ++ public function test_json_arrays_left_by_older_versions_are_discarded_from_typed_properties() ++ { ++ config(['session.serialization' => 'json']); ++ ++ app('session')->forgetDrivers(); ++ FacadesSession::put('stale-collection', [1, 2]); ++ ++ Livewire::test(ComponentWithStaleSessionCollection::class) ++ ->assertSet('list', null); ++ } ++ ++ public function test_stale_enum_backing_values_are_discarded_from_typed_properties() ++ { ++ config(['session.serialization' => 'json']); ++ ++ app('session')->forgetDrivers(); ++ ++ // A scalar backing an enum case that no longer exists (a removed or ++ // renamed case, or a value written before the enum changed). Coercing ++ // it throws a ValueError that must be recovered from, not surfaced. ++ FacadesSession::put('stale-enum', 'archived'); ++ ++ Livewire::test(ComponentWithSessionEnum::class) ++ ->assertSet('status', null); ++ } ++ ++ protected function assertClientAuthoredSynthEnvelopeIsDiscarded($serialization) ++ { ++ config(['session.serialization' => $serialization]); ++ ++ app('session')->forgetDrivers(); ++ ++ Livewire::test(ComponentWithDangerousSessionProperty::class) ++ ->set('value', [ ++ PersistedValueCodec::KEY => [ ++ 'version' => PersistedValueCodec::VERSION, ++ 'value' => [null, [ ++ 's' => 'mdl', ++ 'class' => \Illuminate\Foundation\Auth\User::class, ++ 'key' => 1, ++ ]], ++ ], ++ ]); ++ ++ session()->save(); ++ session()->start(); ++ ++ Livewire::test(ComponentWithDangerousSessionProperty::class) ++ ->assertSet('value', 'safe'); ++ } ++} ++ ++class ComponentWithSessionCollection extends Component ++{ ++ #[Session(key: 'collection')] ++ public ?Collection $list = null; ++ ++ public function mount(): void ++ { ++ $this->list ??= collect(); ++ } ++ ++ public function add(): void ++ { ++ $this->list->push($this->list->count() + 1); ++ } ++ ++ public function render() ++ { ++ return '
{{ $list->implode(", ") }}
'; ++ } ++} ++ ++class ComponentReadingSharedSessionCollection extends Component ++{ ++ #[Session(key: 'collection')] ++ public ?Collection $items = null; ++ ++ public function mount(): void ++ { ++ $this->items ??= collect(); ++ } ++ ++ public function render() ++ { ++ return '
'; ++ } ++} ++ ++class ComponentWithSynthesizedSessionProperties extends Component ++{ ++ #[Session] ++ public ?Carbon $when = null; ++ ++ #[Session] ++ public array $nested = []; ++ ++ public function render() ++ { ++ return '
'; ++ } ++} ++ ++class ComponentWithCustomSynthesizedSessionProperty extends Component ++{ ++ #[Session] ++ public ?CustomSessionValue $value = null; ++ ++ public function mount() ++ { ++ $this->value ??= new CustomSessionValue('persisted'); ++ } ++ ++ public function render() ++ { ++ return '
'; ++ } ++} ++ ++class ComponentWithSessionModel extends Component ++{ ++ #[Session(key: 'article')] ++ public ?SessionArticle $article = null; ++ ++ public function mount() ++ { ++ $this->article ??= SessionArticle::first(); ++ } ++ ++ public function render() ++ { ++ return '
'; ++ } ++} ++ ++class SessionArticle extends Model ++{ ++ use Sushi; ++ ++ protected $rows = [ ++ ['title' => 'First'], ++ ]; ++} ++ ++class CustomSessionValue ++{ ++ public function __construct(public string $value) {} ++} ++ ++class CustomSessionValueSynth extends Synth ++{ ++ public static $key = 'session-value'; ++ ++ public static function match($target) ++ { ++ return $target instanceof CustomSessionValue; ++ } ++ ++ public function dehydrate($target) ++ { ++ return [$target->value, []]; ++ } ++ ++ public function hydrate($value) ++ { ++ return new CustomSessionValue($value); ++ } ++} ++ ++class ComponentWithPrimitiveSessionProperty extends Component ++{ ++ #[Session(key: 'primitive')] ++ public int $count = 0; ++ ++ #[Session(key: 'json-native')] ++ public array $filters = ['search' => '', 'tags' => [1, 2]]; ++ ++ public function render() ++ { ++ return '
'; ++ } ++} ++ ++class ComponentWithRawSessionArray extends Component ++{ ++ #[Session(key: 'legacy-tuple')] ++ public array $value = []; ++ ++ public function render() ++ { ++ return '
'; ++ } ++} ++ ++class ComponentWithDangerousSessionProperty extends Component ++{ ++ #[Session(key: 'dangerous-value')] ++ public $value = 'safe'; ++ ++ public function render() ++ { ++ return '
'; ++ } ++} ++ ++class ComponentWithStaleSessionCollection extends Component ++{ ++ #[Session(key: 'stale-collection')] ++ public ?Collection $list = null; ++ ++ public function render() ++ { ++ return '
'; ++ } ++} ++ ++enum SessionStatus: string ++{ ++ case Draft = 'draft'; ++ case Published = 'published'; ++} ++ ++class ComponentWithSessionEnum extends Component ++{ ++ #[Session(key: 'stale-enum')] ++ public ?SessionStatus $status = null; ++ ++ public function render() ++ { ++ return '
'; ++ } + } diff --git a/tasks/livewire__livewire-10628/tests/test.sh b/tasks/livewire__livewire-10628/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..e3d3238523283b5e3367ccef35f5eb061994fd9e --- /dev/null +++ b/tasks/livewire__livewire-10628/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 5eb0926a9c9bec02e44d02962991aa4e3e0ac2bb > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/livewire__livewire-10628/tests/verifier.py b/tasks/livewire__livewire-10628/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/livewire__livewire-10628/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/livewire__livewire-10629/environment/Dockerfile b/tasks/livewire__livewire-10629/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a3d7201dc5a8d7bdb56810ac57827765abe0d9a7 --- /dev/null +++ b/tasks/livewire__livewire-10629/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/livewire/livewire.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/livewire/livewire.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/livewire/livewire.git +WORKDIR /workspace +RUN git fetch --depth 1 origin db3f789c8fa5ed49a7e1a785e6b0355d6304ec95 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard db3f789c8fa5ed49a7e1a785e6b0355d6304ec95 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base db3f789c8fa5ed49a7e1a785e6b0355d6304ec95 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/livewire__livewire-10629/instruction.md b/tasks/livewire__livewire-10629/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e8025c295a21340c2c63150063dfde06f1771d4e --- /dev/null +++ b/tasks/livewire__livewire-10629/instruction.md @@ -0,0 +1,70 @@ +# Issue + +**Title:** [4.x] Fix wire transition skipped after flux toast auto-dismissed + +## Description + +### Problem + +`wire:transition` currently skips a View Transition whenever there is an open modal dialog or popover: + +```js +if (document.querySelector('dialog:modal, :popover-open')) { + return callback() +} +``` + +This is necessary for open popovers because View Transition pseudo-elements can paint above the top layer. Starting a transition while a popover is open can cause the transition to render over the popover. + +However, `:popover-open` only tells us that the popover itself is open. It does not tell us whether the popover currently has any **visible UI**. + +Some components keep a popover open as a persistent container while its contents are hidden. In that case, `:popover-open` still matches even though there is nothing visible that needs to be protected from the View Transition. + +This causes subsequent Livewire transitions to be skipped unnecessarily. + +### Solution + +Keep the existing behavior for modal dialogs, but for popovers only skip the transition when the popover contains a visible element: + +```js +if (document.querySelector('dialog:modal')) return callback() + +for (let popover of document.querySelectorAll(':popover-open')) { + for (let el of popover.querySelectorAll('*')) { + if (el.checkVisibility()) return callback() + } +} +``` + +`checkVisibility()` lets us determine whether the open popover actually contains visible UI without relying on any framework- or component-specific selectors. + +This keeps the behavior generic and avoids coupling Livewire's transition implementation to a particular component library or DOM structure. + +### Why not just check `:popover-open`? + +An open popover can remain mounted and open while its contents are hidden. Treating every `:popover-open` element as blocking would therefore incorrectly skip transitions when there is no visible popover. + +At the same time, removing the `:popover-open` check entirely would reintroduce the issue where an actually visible popover can be covered by View Transition pseudo-elements. + +The new check handles both cases: + +* **Visible popover** → skip the transition. +* **Open but visually inactive popover** → allow the transition. +* **Modal dialog** → skip the transition as before. + +### Why `checkVisibility()`? + +Checking text content, child count, or specific element names would be unreliable: + +* A popover can contain non-textual UI. +* A popover can contain DOM nodes that are hidden. +* Empty/non-empty DOM structure does not necessarily correspond to visible UI. +* Component-specific selectors would couple Livewire to another package's implementation details. + +`checkVisibility()` directly answers the relevant question: whether there is currently a visible element inside the open popover. + +Fixes: + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `db3f789c8fa5`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10629/solution/patch.diff b/tasks/livewire__livewire-10629/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..60ef7a6f6cddfe1972a4de80559e9014d36b25e1 --- /dev/null +++ b/tasks/livewire__livewire-10629/solution/patch.diff @@ -0,0 +1,121 @@ +diff --git a/js/directives/wire-transition.js b/js/directives/wire-transition.js +index fc61399d..3cf56e58 100644 +--- a/js/directives/wire-transition.js ++++ b/js/directives/wire-transition.js +@@ -44,7 +44,18 @@ export async function transitionDomMutation(fromEl, toEl, callback, options = {} + // Skip entirely if a top-layer element is already open (transitions behind + // it are invisible to the user and the ::view-transition pseudo-elements + // would paint above it during animation)... +- if (document.querySelector('dialog:modal, :popover-open')) return callback() ++ if (document.querySelector('dialog:modal')) return callback() ++ ++ // An open popover only blocks the transition if it has visible descendants. ++ // Some components (e.g. toast hosts) keep an empty popover open as a ++ // persistent container — the host element itself always passes ++ // checkVisibility() while open, so visible *descendants* are the proxy ++ // for "this popover is actually showing UI"... ++ for (let popover of document.querySelectorAll(':popover-open')) { ++ for (let el of popover.querySelectorAll('*')) { ++ if (el.checkVisibility()) return callback() ++ } ++ } + + // Set transition names right before the transition starts (not permanently)... + setTransitionNames(fromEl, options) +diff --git a/src/Features/SupportTransitions/BrowserTest.php b/src/Features/SupportTransitions/BrowserTest.php +index 0622e9db..f6f50daa 100644 +--- a/src/Features/SupportTransitions/BrowserTest.php ++++ b/src/Features/SupportTransitions/BrowserTest.php +@@ -500,4 +500,92 @@ class BrowserTest extends \Tests\BrowserTestCase + ->waitUntil("!$animationsRunning") + ; + } ++ ++ public function test_transition_runs_when_popover_stays_open_without_visible_content() ++ { ++ Livewire::visit( ++ new class extends \Livewire\Component { ++ public $show = false; ++ ++ public function toggle() ++ { ++ $this->show = ! $this->show; ++ } ++ ++ public function render() ++ { ++ return <<<'HTML' ++
++ ++ ++ @if ($show) ++
Hello
++ @endif ++ ++
++ ++
++
++ HTML; ++ } ++ } ++ ) ++ ->waitUntil("document.querySelector('[dusk=toast-host]').matches(':popover-open')") ++ ->tap(fn ($browser) => $browser->script(" ++ window.__startViewTransitionCalled = false ++ let original = document.startViewTransition.bind(document) ++ document.startViewTransition = function (...args) { ++ window.__startViewTransitionCalled = true ++ return original(...args) ++ } ++ ")) ++ ->waitForLivewire()->click('@toggle') ++ ->waitFor('@target') ++ ->assertScript('window.__startViewTransitionCalled', true); ++ } ++ ++ public function test_transition_does_not_run_when_popover_has_visible_content() ++ { ++ Livewire::visit( ++ new class extends \Livewire\Component { ++ public $show = false; ++ ++ public function toggle() ++ { ++ $this->show = ! $this->show; ++ } ++ ++ public function render() ++ { ++ return <<<'HTML' ++
++ ++ ++ @if ($show) ++
Hello
++ @endif ++ ++
++
Visible popover content
++
++
++ HTML; ++ } ++ } ++ ) ++ ->waitUntil("document.querySelector('[dusk=toast-host]').matches(':popover-open')") ++ ->tap(fn ($browser) => $browser->script(" ++ window.__startViewTransitionCalled = false ++ let original = document.startViewTransition.bind(document) ++ document.startViewTransition = function (...args) { ++ window.__startViewTransitionCalled = true ++ return original(...args) ++ } ++ ")) ++ ->waitForLivewire()->click('@toggle') ++ ->waitFor('@target') ++ ->assertScript('window.__startViewTransitionCalled', false); ++ } + } diff --git a/tasks/livewire__livewire-10629/solution/solve.sh b/tasks/livewire__livewire-10629/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/livewire__livewire-10629/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/livewire__livewire-10629/task.toml b/tasks/livewire__livewire-10629/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..2da0c2cd46075315f7bbcaf5a5cf5066d09d6783 --- /dev/null +++ b/tasks/livewire__livewire-10629/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/livewire__livewire-10629" +description = "[4.x] Fix wire transition skipped after flux toast auto-dismissed" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "livewire", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "livewire/livewire" +ref = "db3f789c8fa5ed49a7e1a785e6b0355d6304ec95" +reference = "https://github.com/livewire/livewire/pull/10629" +source_access = "auto" +built_at = "2026-11-16T16:09:51.538746+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:a63b2addca6b4e10ce4848d1ae54c588acdb3d1828476111b96cd3c36bb37de5" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-08-30T12:09:17Z" +diff_format = "unified" +context_files = [ + "js/directives/wire-transition.js", + "src/Features/SupportTransitions/BrowserTest.php", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 101 +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.367411+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:1cc3933f3d663792f5ca2038cb48f521c16715f1543ec9f72f4519964d0e8399" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/livewire__livewire-10629/tests/capture.py b/tasks/livewire__livewire-10629/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/livewire__livewire-10629/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/livewire__livewire-10629/tests/instruction.md b/tasks/livewire__livewire-10629/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e8025c295a21340c2c63150063dfde06f1771d4e --- /dev/null +++ b/tasks/livewire__livewire-10629/tests/instruction.md @@ -0,0 +1,70 @@ +# Issue + +**Title:** [4.x] Fix wire transition skipped after flux toast auto-dismissed + +## Description + +### Problem + +`wire:transition` currently skips a View Transition whenever there is an open modal dialog or popover: + +```js +if (document.querySelector('dialog:modal, :popover-open')) { + return callback() +} +``` + +This is necessary for open popovers because View Transition pseudo-elements can paint above the top layer. Starting a transition while a popover is open can cause the transition to render over the popover. + +However, `:popover-open` only tells us that the popover itself is open. It does not tell us whether the popover currently has any **visible UI**. + +Some components keep a popover open as a persistent container while its contents are hidden. In that case, `:popover-open` still matches even though there is nothing visible that needs to be protected from the View Transition. + +This causes subsequent Livewire transitions to be skipped unnecessarily. + +### Solution + +Keep the existing behavior for modal dialogs, but for popovers only skip the transition when the popover contains a visible element: + +```js +if (document.querySelector('dialog:modal')) return callback() + +for (let popover of document.querySelectorAll(':popover-open')) { + for (let el of popover.querySelectorAll('*')) { + if (el.checkVisibility()) return callback() + } +} +``` + +`checkVisibility()` lets us determine whether the open popover actually contains visible UI without relying on any framework- or component-specific selectors. + +This keeps the behavior generic and avoids coupling Livewire's transition implementation to a particular component library or DOM structure. + +### Why not just check `:popover-open`? + +An open popover can remain mounted and open while its contents are hidden. Treating every `:popover-open` element as blocking would therefore incorrectly skip transitions when there is no visible popover. + +At the same time, removing the `:popover-open` check entirely would reintroduce the issue where an actually visible popover can be covered by View Transition pseudo-elements. + +The new check handles both cases: + +* **Visible popover** → skip the transition. +* **Open but visually inactive popover** → allow the transition. +* **Modal dialog** → skip the transition as before. + +### Why `checkVisibility()`? + +Checking text content, child count, or specific element names would be unreliable: + +* A popover can contain non-textual UI. +* A popover can contain DOM nodes that are hidden. +* Empty/non-empty DOM structure does not necessarily correspond to visible UI. +* Component-specific selectors would couple Livewire to another package's implementation details. + +`checkVisibility()` directly answers the relevant question: whether there is currently a visible element inside the open popover. + +Fixes: + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `db3f789c8fa5`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10629/tests/oracle.patch b/tasks/livewire__livewire-10629/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..60ef7a6f6cddfe1972a4de80559e9014d36b25e1 --- /dev/null +++ b/tasks/livewire__livewire-10629/tests/oracle.patch @@ -0,0 +1,121 @@ +diff --git a/js/directives/wire-transition.js b/js/directives/wire-transition.js +index fc61399d..3cf56e58 100644 +--- a/js/directives/wire-transition.js ++++ b/js/directives/wire-transition.js +@@ -44,7 +44,18 @@ export async function transitionDomMutation(fromEl, toEl, callback, options = {} + // Skip entirely if a top-layer element is already open (transitions behind + // it are invisible to the user and the ::view-transition pseudo-elements + // would paint above it during animation)... +- if (document.querySelector('dialog:modal, :popover-open')) return callback() ++ if (document.querySelector('dialog:modal')) return callback() ++ ++ // An open popover only blocks the transition if it has visible descendants. ++ // Some components (e.g. toast hosts) keep an empty popover open as a ++ // persistent container — the host element itself always passes ++ // checkVisibility() while open, so visible *descendants* are the proxy ++ // for "this popover is actually showing UI"... ++ for (let popover of document.querySelectorAll(':popover-open')) { ++ for (let el of popover.querySelectorAll('*')) { ++ if (el.checkVisibility()) return callback() ++ } ++ } + + // Set transition names right before the transition starts (not permanently)... + setTransitionNames(fromEl, options) +diff --git a/src/Features/SupportTransitions/BrowserTest.php b/src/Features/SupportTransitions/BrowserTest.php +index 0622e9db..f6f50daa 100644 +--- a/src/Features/SupportTransitions/BrowserTest.php ++++ b/src/Features/SupportTransitions/BrowserTest.php +@@ -500,4 +500,92 @@ class BrowserTest extends \Tests\BrowserTestCase + ->waitUntil("!$animationsRunning") + ; + } ++ ++ public function test_transition_runs_when_popover_stays_open_without_visible_content() ++ { ++ Livewire::visit( ++ new class extends \Livewire\Component { ++ public $show = false; ++ ++ public function toggle() ++ { ++ $this->show = ! $this->show; ++ } ++ ++ public function render() ++ { ++ return <<<'HTML' ++
++ ++ ++ @if ($show) ++
Hello
++ @endif ++ ++
++ ++
++
++ HTML; ++ } ++ } ++ ) ++ ->waitUntil("document.querySelector('[dusk=toast-host]').matches(':popover-open')") ++ ->tap(fn ($browser) => $browser->script(" ++ window.__startViewTransitionCalled = false ++ let original = document.startViewTransition.bind(document) ++ document.startViewTransition = function (...args) { ++ window.__startViewTransitionCalled = true ++ return original(...args) ++ } ++ ")) ++ ->waitForLivewire()->click('@toggle') ++ ->waitFor('@target') ++ ->assertScript('window.__startViewTransitionCalled', true); ++ } ++ ++ public function test_transition_does_not_run_when_popover_has_visible_content() ++ { ++ Livewire::visit( ++ new class extends \Livewire\Component { ++ public $show = false; ++ ++ public function toggle() ++ { ++ $this->show = ! $this->show; ++ } ++ ++ public function render() ++ { ++ return <<<'HTML' ++
++ ++ ++ @if ($show) ++
Hello
++ @endif ++ ++
++
Visible popover content
++
++
++ HTML; ++ } ++ } ++ ) ++ ->waitUntil("document.querySelector('[dusk=toast-host]').matches(':popover-open')") ++ ->tap(fn ($browser) => $browser->script(" ++ window.__startViewTransitionCalled = false ++ let original = document.startViewTransition.bind(document) ++ document.startViewTransition = function (...args) { ++ window.__startViewTransitionCalled = true ++ return original(...args) ++ } ++ ")) ++ ->waitForLivewire()->click('@toggle') ++ ->waitFor('@target') ++ ->assertScript('window.__startViewTransitionCalled', false); ++ } + } diff --git a/tasks/livewire__livewire-10629/tests/test.sh b/tasks/livewire__livewire-10629/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..a7cec8421906ba0d1b774dd737665e70ee7f338a --- /dev/null +++ b/tasks/livewire__livewire-10629/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace db3f789c8fa5ed49a7e1a785e6b0355d6304ec95 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/livewire__livewire-10629/tests/verifier.py b/tasks/livewire__livewire-10629/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/livewire__livewire-10629/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/livewire__livewire-10630/environment/Dockerfile b/tasks/livewire__livewire-10630/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..0515480feda0116babce540f58a2e856016c4eec --- /dev/null +++ b/tasks/livewire__livewire-10630/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/livewire/livewire.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/livewire/livewire.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/livewire/livewire.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 16c5b608ab422f8135e16e5cc1e0af3c72d3d1cc 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 16c5b608ab422f8135e16e5cc1e0af3c72d3d1cc \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 16c5b608ab422f8135e16e5cc1e0af3c72d3d1cc \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/livewire__livewire-10630/instruction.md b/tasks/livewire__livewire-10630/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3aaf7c2ecd74678192d11ea3c381c6e4600d9af1 --- /dev/null +++ b/tasks/livewire__livewire-10630/instruction.md @@ -0,0 +1,55 @@ +# Issue + +**Title:** [4.x] Add a trusted-storage codec for synthesized values + +## Description + +## Why + +Features that persist Livewire property values outside the normal browser snapshot need the synth system, but should not each learn about `ComponentContext`, recursive synth tuples, collision-resistant envelopes, or storage trust. + +That plumbing leaked into the first version of #10628 while solving #10250. #10276 gave us the reusable low-level synth mechanism; this PR adds the missing storage-facing layer so the session fix can become the easy change. + +## What + +Add a small `PersistedValueCodec` over `HandleSynths`: + +```php +$stored = $codec->encodeForStorage($value, $component, $path, $storageKey); +$value = $codec->decodeFromStorage($stored, $component, $path, $storageKey); +``` + +The codec: + +- leaves primitives and JSON-native arrays untouched; +- recursively dehydrates values that require a registered Livewire synth; +- owns a strict, versioned envelope so ordinary synth-shaped arrays are never interpreted as metadata; +- signs encoded envelopes with the application encryption key and binds the signature to the caller's resolved storage key; +- reconstructs `ComponentContext` internally; +- preserves nested values and registered custom synths; +- rejects unsigned, modified, wrong-version, or wrong-scope envelopes before `HandleSynths::hydrate()` is reachable. +- converts authentic values whose synthesizer is no longer available into recoverable corrupt state. + +## Trust boundary + +This is intentionally not a general-purpose hydrator. Persisted values can originate from client-writable Livewire properties even when the eventual storage backend is trusted, so storage trust alone is insufficient. The codec authenticates its own output before hydration, using the same application-key security boundary as Livewire snapshots. + +Browser snapshots retain their existing checksum, while URLs and request updates remain on the narrower type-directed `hydrateForUpdate()` path. No arbitrary request value can manufacture a decodable persisted synth envelope. + +## Progressive commits + +1. 🛹 — round-trip a Collection through an authenticated JSON envelope and prove unsigned envelopes never hydrate. +2. 🚲 — define nested/custom synth behavior, strict envelope compatibility, storage-key sharing/scoping, tamper rejection, and outdated-synth recovery. + +## Verification + +- Focused codec coverage: 12 tests, 19 assertions. +- Full stacked unit suite: 1,504 tests, 4,251 assertions; 13 existing skips and 3 existing incomplete tests. +- Independent review confirmed the original unsigned design was exploitable through a client-authored `ModelSynth` envelope; the signed design rejects that path before hydration under both JSON and PHP serializers. +- Built production assets before the complete unit run. + +No user-facing behavior changes in this prerequisite PR. #10628 is the first consumer and retains the original implementation credit to @joshhanley. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `16c5b608ab42`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10630/solution/patch.diff b/tasks/livewire__livewire-10630/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..1e38d7809e6a615166e81f4a7b762cc7d6e34af6 --- /dev/null +++ b/tasks/livewire__livewire-10630/solution/patch.diff @@ -0,0 +1,331 @@ +diff --git a/src/Mechanisms/HandleSynths/CorruptPersistedValueException.php b/src/Mechanisms/HandleSynths/CorruptPersistedValueException.php +new file mode 100644 +index 00000000..4562457f +--- /dev/null ++++ b/src/Mechanisms/HandleSynths/CorruptPersistedValueException.php +@@ -0,0 +1,11 @@ ++requiresSynthesis($value)) return $value; ++ ++ $encoded = $this->synths->dehydrate( ++ $value, ++ new ComponentContext($component), ++ $path, ++ ); ++ ++ return [ ++ static::KEY => [ ++ 'version' => static::VERSION, ++ 'value' => $encoded, ++ 'signature' => $this->signatureFor($encoded, $key), ++ ], ++ ]; ++ } ++ ++ public function decodeFromStorage($value, $component, $path, $key) ++ { ++ if (! $this->isEnvelope($value)) return $value; ++ ++ $envelope = $value[static::KEY]; ++ ++ if (! $this->isValidEnvelope($envelope, $key)) { ++ throw new CorruptPersistedValueException; ++ } ++ ++ try { ++ return $this->synths->hydrate( ++ $envelope['value'], ++ new ComponentContext($component), ++ $path, ++ ); ++ } catch (\Throwable $e) { ++ throw new CorruptPersistedValueException($e); ++ } ++ } ++ ++ protected function isEnvelope($value) ++ { ++ return is_array($value) ++ && count($value) === 1 ++ && array_key_exists(static::KEY, $value); ++ } ++ ++ protected function isValidEnvelope($envelope, $key) ++ { ++ if (! is_array($envelope) || count($envelope) !== 3) return false; ++ ++ if (($envelope['version'] ?? null) !== static::VERSION) return false; ++ ++ if (! array_key_exists('value', $envelope)) return false; ++ ++ if (! Utils::isSyntheticTuple($envelope['value'])) return false; ++ ++ if (! is_string($signature = $envelope['signature'] ?? null)) return false; ++ ++ return hash_equals( ++ $this->signatureFor($envelope['value'], $key), ++ $signature, ++ ); ++ } ++ ++ protected function signatureFor($value, $key) ++ { ++ $payload = json_encode([ ++ 'type' => 'livewire-persisted-value', ++ 'version' => static::VERSION, ++ 'key' => $key, ++ 'value' => $value, ++ ], JSON_THROW_ON_ERROR); ++ ++ return hash_hmac('sha256', $payload, app('encrypter')->getKey()); ++ } ++ ++ protected function requiresSynthesis($value) ++ { ++ if (Utils::isAPrimitive($value)) return false; ++ ++ if (! is_array($value)) return true; ++ ++ foreach ($value as $child) { ++ if ($this->requiresSynthesis($child)) return true; ++ } ++ ++ return false; ++ } ++} +diff --git a/src/Mechanisms/HandleSynths/PersistedValueCodecUnitTest.php b/src/Mechanisms/HandleSynths/PersistedValueCodecUnitTest.php +new file mode 100644 +index 00000000..b43f43d1 +--- /dev/null ++++ b/src/Mechanisms/HandleSynths/PersistedValueCodecUnitTest.php +@@ -0,0 +1,197 @@ ++encodeForStorage(collect([1, 2, 3]), $component, 'items', 'session.items'); ++ $stored = json_decode(json_encode($encoded), true); ++ $decoded = $codec->decodeFromStorage($stored, $component, 'items', 'session.items'); ++ ++ $this->assertInstanceOf(Collection::class, $decoded); ++ $this->assertSame([1, 2, 3], $decoded->all()); ++ } ++ ++ public function test_json_safe_values_are_not_encoded() ++ { ++ $codec = app(PersistedValueCodec::class); ++ $component = new TestComponent; ++ $value = ['search' => '', 'tags' => [1, 2], 'enabled' => true]; ++ ++ $this->assertSame($value, $codec->encodeForStorage($value, $component, 'filters', 'session.filters')); ++ $this->assertSame($value, $codec->decodeFromStorage($value, $component, 'filters', 'session.filters')); ++ } ++ ++ public function test_an_unsigned_envelope_is_never_hydrated() ++ { ++ $codec = app(PersistedValueCodec::class); ++ $component = new TestComponent; ++ $forged = [ ++ PersistedValueCodec::KEY => [ ++ 'version' => PersistedValueCodec::VERSION, ++ 'value' => [['secret'], ['s' => 'clctn', 'class' => Collection::class]], ++ ], ++ ]; ++ ++ $this->expectException(CorruptPersistedValueException::class); ++ ++ $codec->decodeFromStorage($forged, $component, 'items', 'session.items'); ++ } ++ ++ public function test_nested_synthesized_values_round_trip_through_json_storage() ++ { ++ $codec = app(PersistedValueCodec::class); ++ $component = new TestComponent; ++ $date = Carbon::parse('2026-01-15 10:00:00'); ++ $value = ['items' => collect([1, 2]), 'createdAt' => $date]; ++ ++ $encoded = $codec->encodeForStorage($value, $component, 'state', 'session.state'); ++ $stored = json_decode(json_encode($encoded), true); ++ $decoded = $codec->decodeFromStorage($stored, $component, 'state', 'session.state'); ++ ++ $this->assertInstanceOf(Collection::class, $decoded['items']); ++ $this->assertSame([1, 2], $decoded['items']->all()); ++ $this->assertInstanceOf(Carbon::class, $decoded['createdAt']); ++ $this->assertTrue($decoded['createdAt']->equalTo($date)); ++ } ++ ++ public function test_registered_custom_synths_round_trip_through_json_storage() ++ { ++ app(HandleSynths::class)->registerSynth(PersistedValueSynth::class); ++ ++ $codec = app(PersistedValueCodec::class); ++ $component = new TestComponent; ++ ++ $encoded = $codec->encodeForStorage(new PersistedValue('stored'), $component, 'value', 'session.value'); ++ $stored = json_decode(json_encode($encoded), true); ++ $decoded = $codec->decodeFromStorage($stored, $component, 'value', 'session.value'); ++ ++ $this->assertInstanceOf(PersistedValue::class, $decoded); ++ $this->assertSame('stored', $decoded->value); ++ } ++ ++ public function test_bare_synth_tuples_are_not_decoded() ++ { ++ $codec = app(PersistedValueCodec::class); ++ $component = new TestComponent; ++ $tuple = [['one', 'two'], ['s' => 'clctn', 'class' => Collection::class]]; ++ ++ $this->assertSame($tuple, $codec->decodeFromStorage($tuple, $component, 'items', 'session.items')); ++ } ++ ++ public function test_envelopes_with_sibling_application_data_are_not_decoded() ++ { ++ $codec = app(PersistedValueCodec::class); ++ $component = new TestComponent; ++ $encoded = $codec->encodeForStorage(collect([1, 2]), $component, 'items', 'session.items'); ++ $withSiblingData = [...$encoded, 'application' => 'value']; ++ ++ $this->assertSame($withSiblingData, $codec->decodeFromStorage($withSiblingData, $component, 'items', 'session.items')); ++ } ++ ++ public function test_unsupported_envelope_versions_are_rejected() ++ { ++ $codec = app(PersistedValueCodec::class); ++ $component = new TestComponent; ++ $encoded = $codec->encodeForStorage(collect([1, 2]), $component, 'items', 'session.items'); ++ $encoded[PersistedValueCodec::KEY]['version']++; ++ ++ $this->expectException(CorruptPersistedValueException::class); ++ ++ $codec->decodeFromStorage($encoded, $component, 'items', 'session.items'); ++ } ++ ++ public function test_tampered_envelopes_are_rejected_before_hydration() ++ { ++ $codec = app(PersistedValueCodec::class); ++ $component = new TestComponent; ++ $encoded = $codec->encodeForStorage(collect([1, 2]), $component, 'items', 'session.items'); ++ $encoded[PersistedValueCodec::KEY]['value'][0][] = 3; ++ ++ $this->expectException(CorruptPersistedValueException::class); ++ ++ $codec->decodeFromStorage($encoded, $component, 'items', 'session.items'); ++ } ++ ++ public function test_signatures_are_bound_to_the_storage_key() ++ { ++ $codec = app(PersistedValueCodec::class); ++ $component = new TestComponent; ++ $encoded = $codec->encodeForStorage(collect([1, 2]), $component, 'items', 'session.items'); ++ ++ $this->expectException(CorruptPersistedValueException::class); ++ ++ $codec->decodeFromStorage($encoded, $component, 'items', 'session.other'); ++ } ++ ++ public function test_a_shared_storage_key_can_be_decoded_by_another_component_property() ++ { ++ $codec = app(PersistedValueCodec::class); ++ $encoded = $codec->encodeForStorage(collect([1, 2]), new TestComponent, 'items', 'shared'); ++ ++ $decoded = $codec->decodeFromStorage($encoded, new OtherTestComponent, 'renamed', 'shared'); ++ ++ $this->assertInstanceOf(Collection::class, $decoded); ++ $this->assertSame([1, 2], $decoded->all()); ++ } ++ ++ public function test_hydration_failures_are_reported_as_corrupt_persisted_values() ++ { ++ app(HandleSynths::class)->registerSynth(PersistedValueSynth::class); ++ ++ $component = new TestComponent; ++ $encoded = app(PersistedValueCodec::class) ++ ->encodeForStorage(new PersistedValue('stored'), $component, 'value', 'session.value'); ++ $codecWithoutCustomSynth = new PersistedValueCodec(new HandleSynths); ++ ++ try { ++ $codecWithoutCustomSynth->decodeFromStorage($encoded, $component, 'value', 'session.value'); ++ } catch (CorruptPersistedValueException $e) { ++ $this->assertStringContainsString('No synthesizer found', $e->getPrevious()->getMessage()); ++ ++ return; ++ } ++ ++ $this->fail('The outdated persisted value was hydrated.'); ++ } ++} ++ ++class OtherTestComponent extends TestComponent ++{ ++ // ++} ++ ++class PersistedValue ++{ ++ public function __construct(public string $value) {} ++} ++ ++class PersistedValueSynth extends Synth ++{ ++ public static $key = 'persisted-value'; ++ ++ public static function match($target) ++ { ++ return $target instanceof PersistedValue; ++ } ++ ++ public function dehydrate($target) ++ { ++ return [$target->value, []]; ++ } ++ ++ public function hydrate($value) ++ { ++ return new PersistedValue($value); ++ } ++} diff --git a/tasks/livewire__livewire-10630/solution/solve.sh b/tasks/livewire__livewire-10630/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/livewire__livewire-10630/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/livewire__livewire-10630/task.toml b/tasks/livewire__livewire-10630/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..5fe25357f6155b1f7aea3ca8907601dd72503ffb --- /dev/null +++ b/tasks/livewire__livewire-10630/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/livewire__livewire-10630" +description = "[4.x] Add a trusted-storage codec for synthesized values" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "livewire", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "livewire/livewire" +ref = "16c5b608ab422f8135e16e5cc1e0af3c72d3d1cc" +reference = "https://github.com/livewire/livewire/pull/10630" +source_access = "auto" +built_at = "2026-11-16T16:09:51.550784+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:10f5f2637187f7ff1d430f06eb11abdee271358d3e4f76ca3014802b093ff0b2" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-08-29T16:07:47Z" +diff_format = "unified" +context_files = [ + "src/Mechanisms/HandleSynths/CorruptPersistedValueException.php", + "src/Mechanisms/HandleSynths/PersistedValueCodec.php", + "src/Mechanisms/HandleSynths/PersistedValueCodecUnitTest.php", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 313 +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.367919+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:9af8b1153630dccc748aa45dfeca24396f4fb64150581449f871d7996207c013" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/livewire__livewire-10630/tests/capture.py b/tasks/livewire__livewire-10630/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/livewire__livewire-10630/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/livewire__livewire-10630/tests/instruction.md b/tasks/livewire__livewire-10630/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3aaf7c2ecd74678192d11ea3c381c6e4600d9af1 --- /dev/null +++ b/tasks/livewire__livewire-10630/tests/instruction.md @@ -0,0 +1,55 @@ +# Issue + +**Title:** [4.x] Add a trusted-storage codec for synthesized values + +## Description + +## Why + +Features that persist Livewire property values outside the normal browser snapshot need the synth system, but should not each learn about `ComponentContext`, recursive synth tuples, collision-resistant envelopes, or storage trust. + +That plumbing leaked into the first version of #10628 while solving #10250. #10276 gave us the reusable low-level synth mechanism; this PR adds the missing storage-facing layer so the session fix can become the easy change. + +## What + +Add a small `PersistedValueCodec` over `HandleSynths`: + +```php +$stored = $codec->encodeForStorage($value, $component, $path, $storageKey); +$value = $codec->decodeFromStorage($stored, $component, $path, $storageKey); +``` + +The codec: + +- leaves primitives and JSON-native arrays untouched; +- recursively dehydrates values that require a registered Livewire synth; +- owns a strict, versioned envelope so ordinary synth-shaped arrays are never interpreted as metadata; +- signs encoded envelopes with the application encryption key and binds the signature to the caller's resolved storage key; +- reconstructs `ComponentContext` internally; +- preserves nested values and registered custom synths; +- rejects unsigned, modified, wrong-version, or wrong-scope envelopes before `HandleSynths::hydrate()` is reachable. +- converts authentic values whose synthesizer is no longer available into recoverable corrupt state. + +## Trust boundary + +This is intentionally not a general-purpose hydrator. Persisted values can originate from client-writable Livewire properties even when the eventual storage backend is trusted, so storage trust alone is insufficient. The codec authenticates its own output before hydration, using the same application-key security boundary as Livewire snapshots. + +Browser snapshots retain their existing checksum, while URLs and request updates remain on the narrower type-directed `hydrateForUpdate()` path. No arbitrary request value can manufacture a decodable persisted synth envelope. + +## Progressive commits + +1. 🛹 — round-trip a Collection through an authenticated JSON envelope and prove unsigned envelopes never hydrate. +2. 🚲 — define nested/custom synth behavior, strict envelope compatibility, storage-key sharing/scoping, tamper rejection, and outdated-synth recovery. + +## Verification + +- Focused codec coverage: 12 tests, 19 assertions. +- Full stacked unit suite: 1,504 tests, 4,251 assertions; 13 existing skips and 3 existing incomplete tests. +- Independent review confirmed the original unsigned design was exploitable through a client-authored `ModelSynth` envelope; the signed design rejects that path before hydration under both JSON and PHP serializers. +- Built production assets before the complete unit run. + +No user-facing behavior changes in this prerequisite PR. #10628 is the first consumer and retains the original implementation credit to @joshhanley. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `16c5b608ab42`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10630/tests/oracle.patch b/tasks/livewire__livewire-10630/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..1e38d7809e6a615166e81f4a7b762cc7d6e34af6 --- /dev/null +++ b/tasks/livewire__livewire-10630/tests/oracle.patch @@ -0,0 +1,331 @@ +diff --git a/src/Mechanisms/HandleSynths/CorruptPersistedValueException.php b/src/Mechanisms/HandleSynths/CorruptPersistedValueException.php +new file mode 100644 +index 00000000..4562457f +--- /dev/null ++++ b/src/Mechanisms/HandleSynths/CorruptPersistedValueException.php +@@ -0,0 +1,11 @@ ++requiresSynthesis($value)) return $value; ++ ++ $encoded = $this->synths->dehydrate( ++ $value, ++ new ComponentContext($component), ++ $path, ++ ); ++ ++ return [ ++ static::KEY => [ ++ 'version' => static::VERSION, ++ 'value' => $encoded, ++ 'signature' => $this->signatureFor($encoded, $key), ++ ], ++ ]; ++ } ++ ++ public function decodeFromStorage($value, $component, $path, $key) ++ { ++ if (! $this->isEnvelope($value)) return $value; ++ ++ $envelope = $value[static::KEY]; ++ ++ if (! $this->isValidEnvelope($envelope, $key)) { ++ throw new CorruptPersistedValueException; ++ } ++ ++ try { ++ return $this->synths->hydrate( ++ $envelope['value'], ++ new ComponentContext($component), ++ $path, ++ ); ++ } catch (\Throwable $e) { ++ throw new CorruptPersistedValueException($e); ++ } ++ } ++ ++ protected function isEnvelope($value) ++ { ++ return is_array($value) ++ && count($value) === 1 ++ && array_key_exists(static::KEY, $value); ++ } ++ ++ protected function isValidEnvelope($envelope, $key) ++ { ++ if (! is_array($envelope) || count($envelope) !== 3) return false; ++ ++ if (($envelope['version'] ?? null) !== static::VERSION) return false; ++ ++ if (! array_key_exists('value', $envelope)) return false; ++ ++ if (! Utils::isSyntheticTuple($envelope['value'])) return false; ++ ++ if (! is_string($signature = $envelope['signature'] ?? null)) return false; ++ ++ return hash_equals( ++ $this->signatureFor($envelope['value'], $key), ++ $signature, ++ ); ++ } ++ ++ protected function signatureFor($value, $key) ++ { ++ $payload = json_encode([ ++ 'type' => 'livewire-persisted-value', ++ 'version' => static::VERSION, ++ 'key' => $key, ++ 'value' => $value, ++ ], JSON_THROW_ON_ERROR); ++ ++ return hash_hmac('sha256', $payload, app('encrypter')->getKey()); ++ } ++ ++ protected function requiresSynthesis($value) ++ { ++ if (Utils::isAPrimitive($value)) return false; ++ ++ if (! is_array($value)) return true; ++ ++ foreach ($value as $child) { ++ if ($this->requiresSynthesis($child)) return true; ++ } ++ ++ return false; ++ } ++} +diff --git a/src/Mechanisms/HandleSynths/PersistedValueCodecUnitTest.php b/src/Mechanisms/HandleSynths/PersistedValueCodecUnitTest.php +new file mode 100644 +index 00000000..b43f43d1 +--- /dev/null ++++ b/src/Mechanisms/HandleSynths/PersistedValueCodecUnitTest.php +@@ -0,0 +1,197 @@ ++encodeForStorage(collect([1, 2, 3]), $component, 'items', 'session.items'); ++ $stored = json_decode(json_encode($encoded), true); ++ $decoded = $codec->decodeFromStorage($stored, $component, 'items', 'session.items'); ++ ++ $this->assertInstanceOf(Collection::class, $decoded); ++ $this->assertSame([1, 2, 3], $decoded->all()); ++ } ++ ++ public function test_json_safe_values_are_not_encoded() ++ { ++ $codec = app(PersistedValueCodec::class); ++ $component = new TestComponent; ++ $value = ['search' => '', 'tags' => [1, 2], 'enabled' => true]; ++ ++ $this->assertSame($value, $codec->encodeForStorage($value, $component, 'filters', 'session.filters')); ++ $this->assertSame($value, $codec->decodeFromStorage($value, $component, 'filters', 'session.filters')); ++ } ++ ++ public function test_an_unsigned_envelope_is_never_hydrated() ++ { ++ $codec = app(PersistedValueCodec::class); ++ $component = new TestComponent; ++ $forged = [ ++ PersistedValueCodec::KEY => [ ++ 'version' => PersistedValueCodec::VERSION, ++ 'value' => [['secret'], ['s' => 'clctn', 'class' => Collection::class]], ++ ], ++ ]; ++ ++ $this->expectException(CorruptPersistedValueException::class); ++ ++ $codec->decodeFromStorage($forged, $component, 'items', 'session.items'); ++ } ++ ++ public function test_nested_synthesized_values_round_trip_through_json_storage() ++ { ++ $codec = app(PersistedValueCodec::class); ++ $component = new TestComponent; ++ $date = Carbon::parse('2026-01-15 10:00:00'); ++ $value = ['items' => collect([1, 2]), 'createdAt' => $date]; ++ ++ $encoded = $codec->encodeForStorage($value, $component, 'state', 'session.state'); ++ $stored = json_decode(json_encode($encoded), true); ++ $decoded = $codec->decodeFromStorage($stored, $component, 'state', 'session.state'); ++ ++ $this->assertInstanceOf(Collection::class, $decoded['items']); ++ $this->assertSame([1, 2], $decoded['items']->all()); ++ $this->assertInstanceOf(Carbon::class, $decoded['createdAt']); ++ $this->assertTrue($decoded['createdAt']->equalTo($date)); ++ } ++ ++ public function test_registered_custom_synths_round_trip_through_json_storage() ++ { ++ app(HandleSynths::class)->registerSynth(PersistedValueSynth::class); ++ ++ $codec = app(PersistedValueCodec::class); ++ $component = new TestComponent; ++ ++ $encoded = $codec->encodeForStorage(new PersistedValue('stored'), $component, 'value', 'session.value'); ++ $stored = json_decode(json_encode($encoded), true); ++ $decoded = $codec->decodeFromStorage($stored, $component, 'value', 'session.value'); ++ ++ $this->assertInstanceOf(PersistedValue::class, $decoded); ++ $this->assertSame('stored', $decoded->value); ++ } ++ ++ public function test_bare_synth_tuples_are_not_decoded() ++ { ++ $codec = app(PersistedValueCodec::class); ++ $component = new TestComponent; ++ $tuple = [['one', 'two'], ['s' => 'clctn', 'class' => Collection::class]]; ++ ++ $this->assertSame($tuple, $codec->decodeFromStorage($tuple, $component, 'items', 'session.items')); ++ } ++ ++ public function test_envelopes_with_sibling_application_data_are_not_decoded() ++ { ++ $codec = app(PersistedValueCodec::class); ++ $component = new TestComponent; ++ $encoded = $codec->encodeForStorage(collect([1, 2]), $component, 'items', 'session.items'); ++ $withSiblingData = [...$encoded, 'application' => 'value']; ++ ++ $this->assertSame($withSiblingData, $codec->decodeFromStorage($withSiblingData, $component, 'items', 'session.items')); ++ } ++ ++ public function test_unsupported_envelope_versions_are_rejected() ++ { ++ $codec = app(PersistedValueCodec::class); ++ $component = new TestComponent; ++ $encoded = $codec->encodeForStorage(collect([1, 2]), $component, 'items', 'session.items'); ++ $encoded[PersistedValueCodec::KEY]['version']++; ++ ++ $this->expectException(CorruptPersistedValueException::class); ++ ++ $codec->decodeFromStorage($encoded, $component, 'items', 'session.items'); ++ } ++ ++ public function test_tampered_envelopes_are_rejected_before_hydration() ++ { ++ $codec = app(PersistedValueCodec::class); ++ $component = new TestComponent; ++ $encoded = $codec->encodeForStorage(collect([1, 2]), $component, 'items', 'session.items'); ++ $encoded[PersistedValueCodec::KEY]['value'][0][] = 3; ++ ++ $this->expectException(CorruptPersistedValueException::class); ++ ++ $codec->decodeFromStorage($encoded, $component, 'items', 'session.items'); ++ } ++ ++ public function test_signatures_are_bound_to_the_storage_key() ++ { ++ $codec = app(PersistedValueCodec::class); ++ $component = new TestComponent; ++ $encoded = $codec->encodeForStorage(collect([1, 2]), $component, 'items', 'session.items'); ++ ++ $this->expectException(CorruptPersistedValueException::class); ++ ++ $codec->decodeFromStorage($encoded, $component, 'items', 'session.other'); ++ } ++ ++ public function test_a_shared_storage_key_can_be_decoded_by_another_component_property() ++ { ++ $codec = app(PersistedValueCodec::class); ++ $encoded = $codec->encodeForStorage(collect([1, 2]), new TestComponent, 'items', 'shared'); ++ ++ $decoded = $codec->decodeFromStorage($encoded, new OtherTestComponent, 'renamed', 'shared'); ++ ++ $this->assertInstanceOf(Collection::class, $decoded); ++ $this->assertSame([1, 2], $decoded->all()); ++ } ++ ++ public function test_hydration_failures_are_reported_as_corrupt_persisted_values() ++ { ++ app(HandleSynths::class)->registerSynth(PersistedValueSynth::class); ++ ++ $component = new TestComponent; ++ $encoded = app(PersistedValueCodec::class) ++ ->encodeForStorage(new PersistedValue('stored'), $component, 'value', 'session.value'); ++ $codecWithoutCustomSynth = new PersistedValueCodec(new HandleSynths); ++ ++ try { ++ $codecWithoutCustomSynth->decodeFromStorage($encoded, $component, 'value', 'session.value'); ++ } catch (CorruptPersistedValueException $e) { ++ $this->assertStringContainsString('No synthesizer found', $e->getPrevious()->getMessage()); ++ ++ return; ++ } ++ ++ $this->fail('The outdated persisted value was hydrated.'); ++ } ++} ++ ++class OtherTestComponent extends TestComponent ++{ ++ // ++} ++ ++class PersistedValue ++{ ++ public function __construct(public string $value) {} ++} ++ ++class PersistedValueSynth extends Synth ++{ ++ public static $key = 'persisted-value'; ++ ++ public static function match($target) ++ { ++ return $target instanceof PersistedValue; ++ } ++ ++ public function dehydrate($target) ++ { ++ return [$target->value, []]; ++ } ++ ++ public function hydrate($value) ++ { ++ return new PersistedValue($value); ++ } ++} diff --git a/tasks/livewire__livewire-10630/tests/test.sh b/tasks/livewire__livewire-10630/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..f8335d2deefaa0ac95e86f99a3babeaf766ed874 --- /dev/null +++ b/tasks/livewire__livewire-10630/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 16c5b608ab422f8135e16e5cc1e0af3c72d3d1cc > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/livewire__livewire-10630/tests/verifier.py b/tasks/livewire__livewire-10630/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/livewire__livewire-10630/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/livewire__livewire-10633/environment/Dockerfile b/tasks/livewire__livewire-10633/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b7861c3262fab5e5d031bb888db089864f0c7391 --- /dev/null +++ b/tasks/livewire__livewire-10633/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/livewire/livewire.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/livewire/livewire.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/livewire/livewire.git +WORKDIR /workspace +RUN git fetch --depth 1 origin a3064d59dd5f6f5db2f7f81de78948e91551dfe7 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard a3064d59dd5f6f5db2f7f81de78948e91551dfe7 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base a3064d59dd5f6f5db2f7f81de78948e91551dfe7 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/livewire__livewire-10633/instruction.md b/tasks/livewire__livewire-10633/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d2f1afc45c0a7d598e3fb5007d92c26b73034125 --- /dev/null +++ b/tasks/livewire__livewire-10633/instruction.md @@ -0,0 +1,66 @@ +# Issue + +**Title:** [4.x] Reuse resolved models across properties to avoid duplicate queries on update requests + +## Description + +# The Scenario + +#9935 stopped `ModelSynth` from re-querying models already resolved by route binding — but that's the only reuse that exists. Every other Eloquent property still hydrates on its own, so a component holding the same model in two places queries it twice on every update request: + +```php +class UserManager extends Component +{ + public Collection $users; + + public User $selected; + + public function mount() + { + $this->users = User::query()->limit(3)->get(); + $this->selected = $this->users->first(); + } +} +``` + +Every `$refresh`: + +| Source | Query | +|---|---| +| `EloquentCollectionSynth` | `select * from "users" where "users"."id" in (1, 2, 3)` | +| `ModelSynth` | `select * from "users" where "users"."id" = 1 limit 1` | + +The same row is fetched twice because the two synths have no shared state. + +# The Solution + +Models resolved during a request are now remembered in a request-scoped store on `SupportModels` (flushed on `flush-state`, same lifecycle as `PersistentMiddleware::$resolvedRouteModels`): + +* `ModelSynth` checks the store before querying — eagerly at hydration, and again inside the lazy proxy at resolution time (by then a collection may have resolved the model). Freshly queried models are remembered. +* `EloquentCollectionSynth` reuses every model already in the store and runs its restoration query only for the missing keys (order, duplicates, and dropped-missing-model semantics are unchanged). +* The route-bound model lookup from #9935 is absorbed as the store's fallback, so collections now reuse route-bound models too, and `ModelSynth` goes through one code path. + +The repro above drops from 2 queries to 1. Components repeated across a page (or parent/child components sharing the same model) stop issuing one identical query per component payload. + +## Only clean instances are reused + +An instance is only reused while it's indistinguishable from what a fresh query would return. If an instance has been deleted or mutated (`!exists`, `isDirty()`, or `wasChanged()`), the model goes stale for the remainder of the request: nothing reuses it, nothing re-remembers it, and every consumer falls back to today's per-property fresh query. This keeps unsaved mutations in one component from leaking into a sibling component in a pooled update request, and keeps a model deleted mid-request from being resurrected from the store. + +## Semantics worth calling out + +* **Instance sharing**: a model property and "its" row inside a collection can now be the same instance within a request — which is already true at mount time (`$this->selected = $this->users->first()`), for duplicate keys within one collection, and for route-bound models since #9935. Pinned by `test_reused_model_instances_are_shared_within_a_request`. +* **User-land queries are untouched**: a `#[Computed]` that runs `User::query()->get()` still runs its query every request — intercepting arbitrary Eloquent results (e.g. via a `retrieved` listener) would poison the store with partial `select()` models, so the store only ever holds full `newQueryForRestoration()` instances. The guidance for that shape remains storing a `$selectedId` and looking it up in the computed, or `#[Computed(persist: true)]`. +* **PHP < 8.4**: without lazy proxies, properties hydrate eagerly in declaration order, so the store dedupes in that order and instances are shared before actions run (the mutation guards can't apply retroactively). CI covers 8.4/8.5; the guard tests skip below 8.4. +* `retrieved` model events fire once per row instead of once per property — same trade #9935 made. + +# Tests + +Nine new unit tests: reuse in both directions (collection→model and model→collection with a narrowed `whereIn`), same-key model properties sharing one query, the zero-query path when a collection is fully resolvable from the store (including duplicate keys), instance-sharing semantics, the dirty/saved/deleted guards (including the reject-then-save sequence that would serve stale data without the stale-tracking), and per-request store flushing. The reuse tests fail on `main`; the full Unit suite and the `SupportModels` browser tests pass. + +🤖 Generated with [Claude Code](https://claude.com/claude-code) + +https://claude.ai/code/session_01XZqLY9MPvjWoG9Y9ygTfsx + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `a3064d59dd5f`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10633/solution/patch.diff b/tasks/livewire__livewire-10633/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..2276ea9c7fdaabe5d34a0859f63fe075baab7ec8 --- /dev/null +++ b/tasks/livewire__livewire-10633/solution/patch.diff @@ -0,0 +1,593 @@ +diff --git a/src/Features/SupportModels/EloquentCollectionSynth.php b/src/Features/SupportModels/EloquentCollectionSynth.php +index 18bdfa2b..732214b3 100644 +--- a/src/Features/SupportModels/EloquentCollectionSynth.php ++++ b/src/Features/SupportModels/EloquentCollectionSynth.php +@@ -76,16 +76,36 @@ class EloquentCollectionSynth extends Synth { + } + + return $this->makeLazyProxy($class, $meta, function () use ($modelClass, $keys, $meta) { +- // We are using Laravel's method here for restoring the collection, which ensures +- // that all models in the collection are restored in one query, preventing n+1 +- // issues and also only restores models that exist. +- $collection = (new $modelClass)->newQueryForRestoration($keys)->useWritePdo()->get(); +- +- $collection = $collection->keyBy->getKey(); ++ $models = []; ++ $missingKeys = []; ++ ++ // Reuse any models already resolved this request — by route binding (via ++ // SubstituteBindings middleware) or by another hydrated property — so ++ // that only the remaining models need to be queried. ++ foreach (array_unique($keys) as $key) { ++ if ($model = SupportModels::getResolvedModel($modelClass, $key)) { ++ $models[$key] = $model; ++ } else { ++ $missingKeys[] = $key; ++ } ++ } ++ ++ if (count($missingKeys) > 0) { ++ // We are using Laravel's method here for restoring the collection, which ensures ++ // that all models in the collection are restored in one query, preventing n+1 ++ // issues and also only restores models that exist. ++ $collection = (new $modelClass)->newQueryForRestoration($missingKeys)->useWritePdo()->get(); ++ ++ foreach ($collection as $model) { ++ $models[$model->getKey()] = $model; ++ ++ SupportModels::rememberResolvedModel($model); ++ } ++ } + + return new $meta['class']( +- collect($meta['keys'])->map(function ($id) use ($collection) { +- return $collection[$id] ?? null; ++ collect($meta['keys'])->map(function ($id) use ($models) { ++ return $models[$id] ?? null; + })->filter() + ); + }); +diff --git a/src/Features/SupportModels/ModelSynth.php b/src/Features/SupportModels/ModelSynth.php +index 0232d750..6d92cc45 100644 +--- a/src/Features/SupportModels/ModelSynth.php ++++ b/src/Features/SupportModels/ModelSynth.php +@@ -4,7 +4,6 @@ namespace Livewire\Features\SupportModels; + + use Livewire\Mechanisms\HandleComponents\Synthesizers\Synth; + use Livewire\Mechanisms\HandleComponents\ComponentContext; +-use Livewire\Mechanisms\PersistentMiddleware\PersistentMiddleware; + use Illuminate\Queue\SerializesAndRestoresModelIdentifiers; + use Illuminate\Database\Eloquent\Relations\Relation; + use Illuminate\Database\Eloquent\Model; +@@ -74,16 +73,29 @@ class ModelSynth extends Synth { + + $key = $meta['key']; + +- // If this model was already resolved by route binding (via +- // SubstituteBindings middleware), reuse it to avoid a duplicate query. +- $resolvedModel = app(PersistentMiddleware::class)->getResolvedRouteModel($class, $key); ++ // If this model was already resolved this request — by route binding (via ++ // SubstituteBindings middleware) or by another hydrated property — then ++ // reuse it to avoid a duplicate query. ++ $resolvedModel = SupportModels::getResolvedModel($class, $key); + + if ($resolvedModel) { + return $resolvedModel; + } + + return $this->makeLazyProxy($class, $meta, function () use ($class, $key) { +- return (new $class)->newQueryForRestoration($key)->useWritePdo()->firstOrFail(); ++ // Another property (like a collection containing this model) may have ++ // resolved since hydration, so check for a match one more time... ++ $resolvedModel = SupportModels::getResolvedModel($class, $key); ++ ++ if ($resolvedModel) { ++ return $resolvedModel; ++ } ++ ++ $model = (new $class)->newQueryForRestoration($key)->useWritePdo()->firstOrFail(); ++ ++ SupportModels::rememberResolvedModel($model); ++ ++ return $model; + }); + } + +diff --git a/src/Features/SupportModels/SupportModels.php b/src/Features/SupportModels/SupportModels.php +index 7a8b1691..afc9e89c 100644 +--- a/src/Features/SupportModels/SupportModels.php ++++ b/src/Features/SupportModels/SupportModels.php +@@ -2,15 +2,62 @@ + + namespace Livewire\Features\SupportModels; + ++use function Livewire\on; ++use Livewire\Mechanisms\PersistentMiddleware\PersistentMiddleware; + use Livewire\ComponentHook; + + class SupportModels extends ComponentHook + { ++ public static $resolvedModels = []; ++ ++ public static $staleModels = []; ++ + static function provide() + { + app('livewire')->propertySynthesizer([ + ModelSynth::class, + EloquentCollectionSynth::class, + ]); ++ ++ on('flush-state', function () { ++ static::$resolvedModels = []; ++ static::$staleModels = []; ++ }); ++ } ++ ++ static function rememberResolvedModel($model) ++ { ++ $hash = get_class($model).':'.$model->getKey(); ++ ++ // Don't track models that have gone stale, otherwise a deletion or an ++ // update made through the original instance couldn't be detected... ++ if (isset(static::$staleModels[$hash])) return; ++ ++ static::$resolvedModels[$hash] = $model; ++ } ++ ++ static function getResolvedModel($class, $key) ++ { ++ $hash = $class.':'.$key; ++ ++ if (isset(static::$staleModels[$hash])) return null; ++ ++ $model = static::$resolvedModels[$hash] ++ ?? app(PersistentMiddleware::class)->getResolvedRouteModel($class, $key); ++ ++ if (! $model) return null; ++ ++ // Only reuse an instance that is indistinguishable from a freshly queried ++ // one. Once an instance has been deleted or mutated, stop sharing that ++ // model for the rest of the request and fall back to fresh queries... ++ if (! $model->exists || $model->isDirty() || $model->wasChanged()) { ++ static::$staleModels[$hash] = true; ++ ++ unset(static::$resolvedModels[$hash]); ++ ++ return null; ++ } ++ ++ return $model; + } + } +diff --git a/src/Features/SupportModels/UnitTest.php b/src/Features/SupportModels/UnitTest.php +index 76a9072c..e025938b 100644 +--- a/src/Features/SupportModels/UnitTest.php ++++ b/src/Features/SupportModels/UnitTest.php +@@ -325,6 +325,406 @@ class UnitTest extends \Tests\TestCase + $this->assertCount(1, array_values($articleQueries)); + } + ++ public function test_a_model_property_reuses_a_model_already_hydrated_by_a_collection_property() ++ { ++ $component = Livewire::test(new class extends \Livewire\Component { ++ public Collection $articles; ++ ++ public Article $selected; ++ ++ public function mount() { ++ $this->articles = Article::all(); ++ $this->selected = $this->articles->first(); ++ } ++ ++ public function render() { return <<<'HTML' ++
++ @foreach($articles as $article) ++ {{ $article->title.'-'.$loop->index }} ++ @endforeach ++ {{ 'Selected: '.$selected->title }} ++
++ HTML; } ++ }); ++ ++ Article::resolveConnection()->enableQueryLog(); ++ Article::resolveConnection()->flushQueryLog(); ++ ++ $component->call('$refresh') ++ ->assertSee('First-0') ++ ->assertSee('Second-1') ++ ->assertSee('Selected: First'); ++ ++ $this->assertCount(1, Article::resolveConnection()->getQueryLog()); ++ } ++ ++ public function test_a_collection_property_only_queries_models_not_already_hydrated_by_a_model_property() ++ { ++ $component = Livewire::test(new class extends \Livewire\Component { ++ public Article $selected; ++ ++ public Collection $articles; ++ ++ public function mount() { ++ $this->selected = Article::first(); ++ $this->articles = Article::all(); ++ } ++ ++ public function render() { return <<<'HTML' ++
++ {{ 'Selected: '.$selected->title }} ++ @foreach($articles as $article) ++ {{ $article->title.'-'.$loop->index }} ++ @endforeach ++
++ HTML; } ++ }); ++ ++ Article::resolveConnection()->enableQueryLog(); ++ Article::resolveConnection()->flushQueryLog(); ++ ++ $component->call('$refresh') ++ ->assertSee('Selected: First') ++ ->assertSee('First-0') ++ ->assertSee('Second-1'); ++ ++ $queryLog = Article::resolveConnection()->getQueryLog(); ++ ++ $this->assertCount(2, $queryLog); ++ ++ // The collection query should only restore the model that wasn't already ++ // resolved by the model property. Integer keys may be inlined into the ++ // SQL or passed as bindings depending on the Laravel version... ++ [$modelQuery, $collectionQuery] = $queryLog; ++ ++ $this->assertTrue( ++ str_contains($collectionQuery['query'], 'in (2)') || $collectionQuery['bindings'] === [2], ++ 'The collection should only have queried for the unresolved model', ++ ); ++ } ++ ++ public function test_two_model_properties_with_the_same_key_are_hydrated_with_one_query() ++ { ++ $component = Livewire::test(new class extends \Livewire\Component { ++ public Article $first; ++ ++ public Article $second; ++ ++ public function mount() { ++ $this->first = Article::first(); ++ $this->second = Article::first(); ++ } ++ ++ public function render() { return <<<'HTML' ++
{{ 'a:'.$first->title }} {{ 'b:'.$second->title }}
++ HTML; } ++ }); ++ ++ Article::resolveConnection()->enableQueryLog(); ++ Article::resolveConnection()->flushQueryLog(); ++ ++ $component->call('$refresh') ++ ->assertSee('a:First') ++ ->assertSee('b:First'); ++ ++ $this->assertCount(1, Article::resolveConnection()->getQueryLog()); ++ } ++ ++ public function test_reused_model_instances_are_shared_within_a_request() ++ { ++ Livewire::test(new class extends \Livewire\Component { ++ public Collection $articles; ++ ++ public Article $selected; ++ ++ public function mount() { ++ $this->articles = Article::all(); ++ $this->selected = $this->articles->first(); ++ } ++ ++ public function rename() { ++ $this->articles->count(); ++ ++ $this->selected->title = 'Renamed'; ++ } ++ ++ public function render() { return <<<'HTML' ++
++ @foreach($articles as $article) ++ {{ $article->title.'-'.$loop->index }} ++ @endforeach ++
++ HTML; } ++ }) ++ ->call('rename') ++ ->assertSee('Renamed-0') ++ ->assertSee('Second-1'); ++ } ++ ++ public function test_a_collection_is_not_queried_when_all_its_models_are_already_resolved() ++ { ++ $component = Livewire::test(new class extends \Livewire\Component { ++ public Article $one; ++ ++ public Article $two; ++ ++ public Collection $articles; ++ ++ public function mount() { ++ $this->one = Article::find(1); ++ $this->two = Article::find(2); ++ $this->articles = new Collection([Article::find(1), Article::find(1), Article::find(2)]); ++ } ++ ++ public function render() { return <<<'HTML' ++
++ {{ 'a:'.$one->title }} {{ 'b:'.$two->title }} ++ @foreach($articles as $article) ++ {{ $article->title.'-'.$loop->index }} ++ @endforeach ++
++ HTML; } ++ }); ++ ++ Article::resolveConnection()->enableQueryLog(); ++ Article::resolveConnection()->flushQueryLog(); ++ ++ $component->call('$refresh') ++ ->assertSee('a:First') ++ ->assertSee('b:Second') ++ ->assertSee('First-0') ++ ->assertSee('First-1') ++ ->assertSee('Second-2'); ++ ++ $this->assertCount(2, Article::resolveConnection()->getQueryLog()); ++ } ++ ++ public function test_resolved_models_are_not_reused_across_requests() ++ { ++ $component = Livewire::test(new class extends \Livewire\Component { ++ public Article $article; ++ ++ public function mount() { ++ $this->article = Article::first(); ++ } ++ ++ public function render() { return <<<'HTML' ++
{{ $article->title }}
++ HTML; } ++ }); ++ ++ Article::resolveConnection()->enableQueryLog(); ++ Article::resolveConnection()->flushQueryLog(); ++ ++ $component->call('$refresh')->assertSee('First'); ++ $component->call('$refresh')->assertSee('First'); ++ ++ $this->assertCount(2, Article::resolveConnection()->getQueryLog()); ++ } ++ ++ public function test_a_mutated_model_is_not_reused_by_other_properties() ++ { ++ // On earlier versions there are no lazy proxies, so properties hydrate ++ // eagerly before any mutations and share the still-clean instance... ++ if (PHP_VERSION_ID < 80400) $this->markTestSkipped('Requires lazy model proxies'); ++ ++ $component = Livewire::test(new class extends \Livewire\Component { ++ public Article $first; ++ ++ public Article $second; ++ ++ public function mount() { ++ $this->first = Article::first(); ++ $this->second = Article::first(); ++ } ++ ++ public function rename() { ++ $this->first->title = 'Draft'; ++ } ++ ++ public function render() { return <<<'HTML' ++
{{ 'a:'.$first->title }} {{ 'b:'.$second->title }}
++ HTML; } ++ }); ++ ++ Article::resolveConnection()->enableQueryLog(); ++ Article::resolveConnection()->flushQueryLog(); ++ ++ // The unsaved mutation on $first shouldn't leak into $second — it ++ // should fall through to a fresh query instead... ++ $component->call('rename') ++ ->assertSee('a:Draft') ++ ->assertSee('b:First'); ++ ++ $this->assertCount(2, Article::resolveConnection()->getQueryLog()); ++ } ++ ++ public function test_a_deleted_model_is_not_reused_when_hydrating_a_collection() ++ { ++ // On earlier versions there are no lazy proxies, so the collection is ++ // hydrated eagerly before the deletion, like it is on main... ++ if (PHP_VERSION_ID < 80400) $this->markTestSkipped('Requires lazy model proxies'); ++ ++ $this->resetMutableArticles(); ++ ++ Livewire::test(new class extends \Livewire\Component { ++ public Collection $articles; ++ ++ public MutableArticle $selected; ++ ++ public function mount() { ++ $this->articles = MutableArticle::all(); ++ $this->selected = $this->articles->first(); ++ } ++ ++ public function deleteSelected() { ++ $this->selected->delete(); ++ } ++ ++ public function render() { return <<<'HTML' ++
++ @foreach($articles as $article) ++ {{ $article->title.'-'.$loop->index }} ++ @endforeach ++
++ HTML; } ++ }) ++ ->call('deleteSelected') ++ ->assertDontSee('First-') ++ ->assertSee('Second-0'); ++ } ++ ++ public function test_a_saved_model_is_not_reused_by_other_properties() ++ { ++ if (PHP_VERSION_ID < 80400) $this->markTestSkipped('Requires lazy model proxies'); ++ ++ $this->resetMutableArticles(); ++ ++ $component = Livewire::test(new class extends \Livewire\Component { ++ public MutableArticle $first; ++ ++ public MutableArticle $second; ++ ++ public function mount() { ++ $this->first = MutableArticle::find(1); ++ $this->second = MutableArticle::find(1); ++ } ++ ++ public function rename() { ++ $this->first->update(['title' => 'Renamed']); ++ } ++ ++ public function render() { return <<<'HTML' ++
{{ 'a:'.$first->title }} {{ 'b:'.$second->title }}
++ HTML; } ++ }); ++ ++ MutableArticle::resolveConnection()->enableQueryLog(); ++ MutableArticle::resolveConnection()->flushQueryLog(); ++ ++ // The saved model shouldn't be reused for $second — it should fall ++ // through to a fresh query, which reads the same saved title... ++ $component->call('rename') ++ ->assertSee('a:Renamed') ++ ->assertSee('b:Renamed'); ++ ++ $selects = array_filter( ++ MutableArticle::resolveConnection()->getQueryLog(), ++ fn ($q) => str_starts_with($q['query'], 'select'), ++ ); ++ ++ $this->assertCount(2, $selects); ++ } ++ ++ public function test_a_model_saved_after_its_reuse_was_rejected_is_not_served_stale() ++ { ++ if (PHP_VERSION_ID < 80400) $this->markTestSkipped('Requires lazy model proxies'); ++ ++ $this->resetMutableArticles(); ++ ++ Livewire::test(new class extends \Livewire\Component { ++ public MutableArticle $first; ++ ++ public MutableArticle $second; ++ ++ public Collection $articles; ++ ++ public function mount() { ++ $this->first = MutableArticle::find(1); ++ $this->second = MutableArticle::find(1); ++ $this->articles = MutableArticle::all(); ++ } ++ ++ public function rename() { ++ // Once a mutated instance is encountered, the model shouldn't be ++ // shared for the rest of the request — even after the collection ++ // resolves a clean instance while the mutation is unsaved... ++ $this->first->title = 'Renamed'; ++ ++ $this->articles->count(); ++ ++ $this->first->save(); ++ } ++ ++ public function render() { return <<<'HTML' ++
{{ 'b:'.$second->title }}
++ HTML; } ++ }) ++ ->call('rename') ++ ->assertSee('b:Renamed'); ++ } ++ ++ public function test_a_model_deleted_after_its_reuse_was_rejected_is_not_resurrected() ++ { ++ if (PHP_VERSION_ID < 80400) $this->markTestSkipped('Requires lazy model proxies'); ++ ++ $this->resetMutableArticles(); ++ ++ Livewire::test(new class extends \Livewire\Component { ++ public MutableArticle $selected; ++ ++ public Collection $articles; ++ ++ public Collection $others; ++ ++ public function mount() { ++ $this->selected = MutableArticle::find(1); ++ $this->articles = MutableArticle::all(); ++ $this->others = MutableArticle::all(); ++ } ++ ++ public function deleteSelected() { ++ $this->selected->title = 'Doomed'; ++ ++ $this->articles->count(); ++ ++ $this->selected->delete(); ++ } ++ ++ public function render() { return <<<'HTML' ++
++ @foreach($others as $article) ++ {{ $article->title.'-'.$loop->index }} ++ @endforeach ++
++ HTML; } ++ }) ++ ->call('deleteSelected') ++ ->assertDontSee('First-') ++ ->assertDontSee('Doomed-') ++ ->assertSee('Second-0'); ++ } ++ ++ protected function resetMutableArticles() ++ { ++ // Reset the table as these tests modify or delete its rows... ++ MutableArticle::query()->delete(); ++ MutableArticle::insert([ ++ ['id' => 1, 'title' => 'First'], ++ ['id' => 2, 'title' => 'Second'], ++ ]); ++ } ++ + public function test_hydrating_an_empty_eloquent_collection_does_not_trigger_deprecations() + { + $component = Livewire::test(new class extends \Livewire\Component { +@@ -384,6 +784,19 @@ class Article extends Model + ]; + } + ++// Uses its own table so modifying or deleting rows doesn't affect other tests... ++class MutableArticle extends Model ++{ ++ use Sushi; ++ ++ protected $guarded = []; ++ ++ protected $rows = [ ++ ['title' => 'First'], ++ ['title' => 'Second'], ++ ]; ++} ++ + // Simulates tightenco/parental's HasParent trait, which overrides + // getTable() and getMorphClass() to return the parent's values so + // that polymorphic relations use the parent's table. diff --git a/tasks/livewire__livewire-10633/solution/solve.sh b/tasks/livewire__livewire-10633/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/livewire__livewire-10633/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/livewire__livewire-10633/task.toml b/tasks/livewire__livewire-10633/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..3807e20de513880a7b1279f08f9745a031fc1d55 --- /dev/null +++ b/tasks/livewire__livewire-10633/task.toml @@ -0,0 +1,71 @@ +version = "1.0" + +[task] +name = "trending/livewire__livewire-10633" +description = "[4.x] Reuse resolved models across properties to avoid duplicate queries on update requests" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "livewire", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "livewire/livewire" +ref = "a3064d59dd5f6f5db2f7f81de78948e91551dfe7" +reference = "https://github.com/livewire/livewire/pull/10633" +source_access = "auto" +built_at = "2026-11-16T16:09:51.533341+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:7ae2ef80bbdb222b16707180aa66abb26bccc916f7405870ac11c56638615c36" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-08-30T12:29:58Z" +diff_format = "unified" +context_files = [ + "src/Features/SupportModels/EloquentCollectionSynth.php", + "src/Features/SupportModels/ModelSynth.php", + "src/Features/SupportModels/SupportModels.php", + "src/Features/SupportModels/UnitTest.php", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 518 +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.368381+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:bd16521b85539f865b378312637655ca8ab5a3902f455f507e116f27e1d0eac0" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/livewire__livewire-10633/tests/capture.py b/tasks/livewire__livewire-10633/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/livewire__livewire-10633/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/livewire__livewire-10633/tests/instruction.md b/tasks/livewire__livewire-10633/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d2f1afc45c0a7d598e3fb5007d92c26b73034125 --- /dev/null +++ b/tasks/livewire__livewire-10633/tests/instruction.md @@ -0,0 +1,66 @@ +# Issue + +**Title:** [4.x] Reuse resolved models across properties to avoid duplicate queries on update requests + +## Description + +# The Scenario + +#9935 stopped `ModelSynth` from re-querying models already resolved by route binding — but that's the only reuse that exists. Every other Eloquent property still hydrates on its own, so a component holding the same model in two places queries it twice on every update request: + +```php +class UserManager extends Component +{ + public Collection $users; + + public User $selected; + + public function mount() + { + $this->users = User::query()->limit(3)->get(); + $this->selected = $this->users->first(); + } +} +``` + +Every `$refresh`: + +| Source | Query | +|---|---| +| `EloquentCollectionSynth` | `select * from "users" where "users"."id" in (1, 2, 3)` | +| `ModelSynth` | `select * from "users" where "users"."id" = 1 limit 1` | + +The same row is fetched twice because the two synths have no shared state. + +# The Solution + +Models resolved during a request are now remembered in a request-scoped store on `SupportModels` (flushed on `flush-state`, same lifecycle as `PersistentMiddleware::$resolvedRouteModels`): + +* `ModelSynth` checks the store before querying — eagerly at hydration, and again inside the lazy proxy at resolution time (by then a collection may have resolved the model). Freshly queried models are remembered. +* `EloquentCollectionSynth` reuses every model already in the store and runs its restoration query only for the missing keys (order, duplicates, and dropped-missing-model semantics are unchanged). +* The route-bound model lookup from #9935 is absorbed as the store's fallback, so collections now reuse route-bound models too, and `ModelSynth` goes through one code path. + +The repro above drops from 2 queries to 1. Components repeated across a page (or parent/child components sharing the same model) stop issuing one identical query per component payload. + +## Only clean instances are reused + +An instance is only reused while it's indistinguishable from what a fresh query would return. If an instance has been deleted or mutated (`!exists`, `isDirty()`, or `wasChanged()`), the model goes stale for the remainder of the request: nothing reuses it, nothing re-remembers it, and every consumer falls back to today's per-property fresh query. This keeps unsaved mutations in one component from leaking into a sibling component in a pooled update request, and keeps a model deleted mid-request from being resurrected from the store. + +## Semantics worth calling out + +* **Instance sharing**: a model property and "its" row inside a collection can now be the same instance within a request — which is already true at mount time (`$this->selected = $this->users->first()`), for duplicate keys within one collection, and for route-bound models since #9935. Pinned by `test_reused_model_instances_are_shared_within_a_request`. +* **User-land queries are untouched**: a `#[Computed]` that runs `User::query()->get()` still runs its query every request — intercepting arbitrary Eloquent results (e.g. via a `retrieved` listener) would poison the store with partial `select()` models, so the store only ever holds full `newQueryForRestoration()` instances. The guidance for that shape remains storing a `$selectedId` and looking it up in the computed, or `#[Computed(persist: true)]`. +* **PHP < 8.4**: without lazy proxies, properties hydrate eagerly in declaration order, so the store dedupes in that order and instances are shared before actions run (the mutation guards can't apply retroactively). CI covers 8.4/8.5; the guard tests skip below 8.4. +* `retrieved` model events fire once per row instead of once per property — same trade #9935 made. + +# Tests + +Nine new unit tests: reuse in both directions (collection→model and model→collection with a narrowed `whereIn`), same-key model properties sharing one query, the zero-query path when a collection is fully resolvable from the store (including duplicate keys), instance-sharing semantics, the dirty/saved/deleted guards (including the reject-then-save sequence that would serve stale data without the stale-tracking), and per-request store flushing. The reuse tests fail on `main`; the full Unit suite and the `SupportModels` browser tests pass. + +🤖 Generated with [Claude Code](https://claude.com/claude-code) + +https://claude.ai/code/session_01XZqLY9MPvjWoG9Y9ygTfsx + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `a3064d59dd5f`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10633/tests/oracle.patch b/tasks/livewire__livewire-10633/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..2276ea9c7fdaabe5d34a0859f63fe075baab7ec8 --- /dev/null +++ b/tasks/livewire__livewire-10633/tests/oracle.patch @@ -0,0 +1,593 @@ +diff --git a/src/Features/SupportModels/EloquentCollectionSynth.php b/src/Features/SupportModels/EloquentCollectionSynth.php +index 18bdfa2b..732214b3 100644 +--- a/src/Features/SupportModels/EloquentCollectionSynth.php ++++ b/src/Features/SupportModels/EloquentCollectionSynth.php +@@ -76,16 +76,36 @@ class EloquentCollectionSynth extends Synth { + } + + return $this->makeLazyProxy($class, $meta, function () use ($modelClass, $keys, $meta) { +- // We are using Laravel's method here for restoring the collection, which ensures +- // that all models in the collection are restored in one query, preventing n+1 +- // issues and also only restores models that exist. +- $collection = (new $modelClass)->newQueryForRestoration($keys)->useWritePdo()->get(); +- +- $collection = $collection->keyBy->getKey(); ++ $models = []; ++ $missingKeys = []; ++ ++ // Reuse any models already resolved this request — by route binding (via ++ // SubstituteBindings middleware) or by another hydrated property — so ++ // that only the remaining models need to be queried. ++ foreach (array_unique($keys) as $key) { ++ if ($model = SupportModels::getResolvedModel($modelClass, $key)) { ++ $models[$key] = $model; ++ } else { ++ $missingKeys[] = $key; ++ } ++ } ++ ++ if (count($missingKeys) > 0) { ++ // We are using Laravel's method here for restoring the collection, which ensures ++ // that all models in the collection are restored in one query, preventing n+1 ++ // issues and also only restores models that exist. ++ $collection = (new $modelClass)->newQueryForRestoration($missingKeys)->useWritePdo()->get(); ++ ++ foreach ($collection as $model) { ++ $models[$model->getKey()] = $model; ++ ++ SupportModels::rememberResolvedModel($model); ++ } ++ } + + return new $meta['class']( +- collect($meta['keys'])->map(function ($id) use ($collection) { +- return $collection[$id] ?? null; ++ collect($meta['keys'])->map(function ($id) use ($models) { ++ return $models[$id] ?? null; + })->filter() + ); + }); +diff --git a/src/Features/SupportModels/ModelSynth.php b/src/Features/SupportModels/ModelSynth.php +index 0232d750..6d92cc45 100644 +--- a/src/Features/SupportModels/ModelSynth.php ++++ b/src/Features/SupportModels/ModelSynth.php +@@ -4,7 +4,6 @@ namespace Livewire\Features\SupportModels; + + use Livewire\Mechanisms\HandleComponents\Synthesizers\Synth; + use Livewire\Mechanisms\HandleComponents\ComponentContext; +-use Livewire\Mechanisms\PersistentMiddleware\PersistentMiddleware; + use Illuminate\Queue\SerializesAndRestoresModelIdentifiers; + use Illuminate\Database\Eloquent\Relations\Relation; + use Illuminate\Database\Eloquent\Model; +@@ -74,16 +73,29 @@ class ModelSynth extends Synth { + + $key = $meta['key']; + +- // If this model was already resolved by route binding (via +- // SubstituteBindings middleware), reuse it to avoid a duplicate query. +- $resolvedModel = app(PersistentMiddleware::class)->getResolvedRouteModel($class, $key); ++ // If this model was already resolved this request — by route binding (via ++ // SubstituteBindings middleware) or by another hydrated property — then ++ // reuse it to avoid a duplicate query. ++ $resolvedModel = SupportModels::getResolvedModel($class, $key); + + if ($resolvedModel) { + return $resolvedModel; + } + + return $this->makeLazyProxy($class, $meta, function () use ($class, $key) { +- return (new $class)->newQueryForRestoration($key)->useWritePdo()->firstOrFail(); ++ // Another property (like a collection containing this model) may have ++ // resolved since hydration, so check for a match one more time... ++ $resolvedModel = SupportModels::getResolvedModel($class, $key); ++ ++ if ($resolvedModel) { ++ return $resolvedModel; ++ } ++ ++ $model = (new $class)->newQueryForRestoration($key)->useWritePdo()->firstOrFail(); ++ ++ SupportModels::rememberResolvedModel($model); ++ ++ return $model; + }); + } + +diff --git a/src/Features/SupportModels/SupportModels.php b/src/Features/SupportModels/SupportModels.php +index 7a8b1691..afc9e89c 100644 +--- a/src/Features/SupportModels/SupportModels.php ++++ b/src/Features/SupportModels/SupportModels.php +@@ -2,15 +2,62 @@ + + namespace Livewire\Features\SupportModels; + ++use function Livewire\on; ++use Livewire\Mechanisms\PersistentMiddleware\PersistentMiddleware; + use Livewire\ComponentHook; + + class SupportModels extends ComponentHook + { ++ public static $resolvedModels = []; ++ ++ public static $staleModels = []; ++ + static function provide() + { + app('livewire')->propertySynthesizer([ + ModelSynth::class, + EloquentCollectionSynth::class, + ]); ++ ++ on('flush-state', function () { ++ static::$resolvedModels = []; ++ static::$staleModels = []; ++ }); ++ } ++ ++ static function rememberResolvedModel($model) ++ { ++ $hash = get_class($model).':'.$model->getKey(); ++ ++ // Don't track models that have gone stale, otherwise a deletion or an ++ // update made through the original instance couldn't be detected... ++ if (isset(static::$staleModels[$hash])) return; ++ ++ static::$resolvedModels[$hash] = $model; ++ } ++ ++ static function getResolvedModel($class, $key) ++ { ++ $hash = $class.':'.$key; ++ ++ if (isset(static::$staleModels[$hash])) return null; ++ ++ $model = static::$resolvedModels[$hash] ++ ?? app(PersistentMiddleware::class)->getResolvedRouteModel($class, $key); ++ ++ if (! $model) return null; ++ ++ // Only reuse an instance that is indistinguishable from a freshly queried ++ // one. Once an instance has been deleted or mutated, stop sharing that ++ // model for the rest of the request and fall back to fresh queries... ++ if (! $model->exists || $model->isDirty() || $model->wasChanged()) { ++ static::$staleModels[$hash] = true; ++ ++ unset(static::$resolvedModels[$hash]); ++ ++ return null; ++ } ++ ++ return $model; + } + } +diff --git a/src/Features/SupportModels/UnitTest.php b/src/Features/SupportModels/UnitTest.php +index 76a9072c..e025938b 100644 +--- a/src/Features/SupportModels/UnitTest.php ++++ b/src/Features/SupportModels/UnitTest.php +@@ -325,6 +325,406 @@ class UnitTest extends \Tests\TestCase + $this->assertCount(1, array_values($articleQueries)); + } + ++ public function test_a_model_property_reuses_a_model_already_hydrated_by_a_collection_property() ++ { ++ $component = Livewire::test(new class extends \Livewire\Component { ++ public Collection $articles; ++ ++ public Article $selected; ++ ++ public function mount() { ++ $this->articles = Article::all(); ++ $this->selected = $this->articles->first(); ++ } ++ ++ public function render() { return <<<'HTML' ++
++ @foreach($articles as $article) ++ {{ $article->title.'-'.$loop->index }} ++ @endforeach ++ {{ 'Selected: '.$selected->title }} ++
++ HTML; } ++ }); ++ ++ Article::resolveConnection()->enableQueryLog(); ++ Article::resolveConnection()->flushQueryLog(); ++ ++ $component->call('$refresh') ++ ->assertSee('First-0') ++ ->assertSee('Second-1') ++ ->assertSee('Selected: First'); ++ ++ $this->assertCount(1, Article::resolveConnection()->getQueryLog()); ++ } ++ ++ public function test_a_collection_property_only_queries_models_not_already_hydrated_by_a_model_property() ++ { ++ $component = Livewire::test(new class extends \Livewire\Component { ++ public Article $selected; ++ ++ public Collection $articles; ++ ++ public function mount() { ++ $this->selected = Article::first(); ++ $this->articles = Article::all(); ++ } ++ ++ public function render() { return <<<'HTML' ++
++ {{ 'Selected: '.$selected->title }} ++ @foreach($articles as $article) ++ {{ $article->title.'-'.$loop->index }} ++ @endforeach ++
++ HTML; } ++ }); ++ ++ Article::resolveConnection()->enableQueryLog(); ++ Article::resolveConnection()->flushQueryLog(); ++ ++ $component->call('$refresh') ++ ->assertSee('Selected: First') ++ ->assertSee('First-0') ++ ->assertSee('Second-1'); ++ ++ $queryLog = Article::resolveConnection()->getQueryLog(); ++ ++ $this->assertCount(2, $queryLog); ++ ++ // The collection query should only restore the model that wasn't already ++ // resolved by the model property. Integer keys may be inlined into the ++ // SQL or passed as bindings depending on the Laravel version... ++ [$modelQuery, $collectionQuery] = $queryLog; ++ ++ $this->assertTrue( ++ str_contains($collectionQuery['query'], 'in (2)') || $collectionQuery['bindings'] === [2], ++ 'The collection should only have queried for the unresolved model', ++ ); ++ } ++ ++ public function test_two_model_properties_with_the_same_key_are_hydrated_with_one_query() ++ { ++ $component = Livewire::test(new class extends \Livewire\Component { ++ public Article $first; ++ ++ public Article $second; ++ ++ public function mount() { ++ $this->first = Article::first(); ++ $this->second = Article::first(); ++ } ++ ++ public function render() { return <<<'HTML' ++
{{ 'a:'.$first->title }} {{ 'b:'.$second->title }}
++ HTML; } ++ }); ++ ++ Article::resolveConnection()->enableQueryLog(); ++ Article::resolveConnection()->flushQueryLog(); ++ ++ $component->call('$refresh') ++ ->assertSee('a:First') ++ ->assertSee('b:First'); ++ ++ $this->assertCount(1, Article::resolveConnection()->getQueryLog()); ++ } ++ ++ public function test_reused_model_instances_are_shared_within_a_request() ++ { ++ Livewire::test(new class extends \Livewire\Component { ++ public Collection $articles; ++ ++ public Article $selected; ++ ++ public function mount() { ++ $this->articles = Article::all(); ++ $this->selected = $this->articles->first(); ++ } ++ ++ public function rename() { ++ $this->articles->count(); ++ ++ $this->selected->title = 'Renamed'; ++ } ++ ++ public function render() { return <<<'HTML' ++
++ @foreach($articles as $article) ++ {{ $article->title.'-'.$loop->index }} ++ @endforeach ++
++ HTML; } ++ }) ++ ->call('rename') ++ ->assertSee('Renamed-0') ++ ->assertSee('Second-1'); ++ } ++ ++ public function test_a_collection_is_not_queried_when_all_its_models_are_already_resolved() ++ { ++ $component = Livewire::test(new class extends \Livewire\Component { ++ public Article $one; ++ ++ public Article $two; ++ ++ public Collection $articles; ++ ++ public function mount() { ++ $this->one = Article::find(1); ++ $this->two = Article::find(2); ++ $this->articles = new Collection([Article::find(1), Article::find(1), Article::find(2)]); ++ } ++ ++ public function render() { return <<<'HTML' ++
++ {{ 'a:'.$one->title }} {{ 'b:'.$two->title }} ++ @foreach($articles as $article) ++ {{ $article->title.'-'.$loop->index }} ++ @endforeach ++
++ HTML; } ++ }); ++ ++ Article::resolveConnection()->enableQueryLog(); ++ Article::resolveConnection()->flushQueryLog(); ++ ++ $component->call('$refresh') ++ ->assertSee('a:First') ++ ->assertSee('b:Second') ++ ->assertSee('First-0') ++ ->assertSee('First-1') ++ ->assertSee('Second-2'); ++ ++ $this->assertCount(2, Article::resolveConnection()->getQueryLog()); ++ } ++ ++ public function test_resolved_models_are_not_reused_across_requests() ++ { ++ $component = Livewire::test(new class extends \Livewire\Component { ++ public Article $article; ++ ++ public function mount() { ++ $this->article = Article::first(); ++ } ++ ++ public function render() { return <<<'HTML' ++
{{ $article->title }}
++ HTML; } ++ }); ++ ++ Article::resolveConnection()->enableQueryLog(); ++ Article::resolveConnection()->flushQueryLog(); ++ ++ $component->call('$refresh')->assertSee('First'); ++ $component->call('$refresh')->assertSee('First'); ++ ++ $this->assertCount(2, Article::resolveConnection()->getQueryLog()); ++ } ++ ++ public function test_a_mutated_model_is_not_reused_by_other_properties() ++ { ++ // On earlier versions there are no lazy proxies, so properties hydrate ++ // eagerly before any mutations and share the still-clean instance... ++ if (PHP_VERSION_ID < 80400) $this->markTestSkipped('Requires lazy model proxies'); ++ ++ $component = Livewire::test(new class extends \Livewire\Component { ++ public Article $first; ++ ++ public Article $second; ++ ++ public function mount() { ++ $this->first = Article::first(); ++ $this->second = Article::first(); ++ } ++ ++ public function rename() { ++ $this->first->title = 'Draft'; ++ } ++ ++ public function render() { return <<<'HTML' ++
{{ 'a:'.$first->title }} {{ 'b:'.$second->title }}
++ HTML; } ++ }); ++ ++ Article::resolveConnection()->enableQueryLog(); ++ Article::resolveConnection()->flushQueryLog(); ++ ++ // The unsaved mutation on $first shouldn't leak into $second — it ++ // should fall through to a fresh query instead... ++ $component->call('rename') ++ ->assertSee('a:Draft') ++ ->assertSee('b:First'); ++ ++ $this->assertCount(2, Article::resolveConnection()->getQueryLog()); ++ } ++ ++ public function test_a_deleted_model_is_not_reused_when_hydrating_a_collection() ++ { ++ // On earlier versions there are no lazy proxies, so the collection is ++ // hydrated eagerly before the deletion, like it is on main... ++ if (PHP_VERSION_ID < 80400) $this->markTestSkipped('Requires lazy model proxies'); ++ ++ $this->resetMutableArticles(); ++ ++ Livewire::test(new class extends \Livewire\Component { ++ public Collection $articles; ++ ++ public MutableArticle $selected; ++ ++ public function mount() { ++ $this->articles = MutableArticle::all(); ++ $this->selected = $this->articles->first(); ++ } ++ ++ public function deleteSelected() { ++ $this->selected->delete(); ++ } ++ ++ public function render() { return <<<'HTML' ++
++ @foreach($articles as $article) ++ {{ $article->title.'-'.$loop->index }} ++ @endforeach ++
++ HTML; } ++ }) ++ ->call('deleteSelected') ++ ->assertDontSee('First-') ++ ->assertSee('Second-0'); ++ } ++ ++ public function test_a_saved_model_is_not_reused_by_other_properties() ++ { ++ if (PHP_VERSION_ID < 80400) $this->markTestSkipped('Requires lazy model proxies'); ++ ++ $this->resetMutableArticles(); ++ ++ $component = Livewire::test(new class extends \Livewire\Component { ++ public MutableArticle $first; ++ ++ public MutableArticle $second; ++ ++ public function mount() { ++ $this->first = MutableArticle::find(1); ++ $this->second = MutableArticle::find(1); ++ } ++ ++ public function rename() { ++ $this->first->update(['title' => 'Renamed']); ++ } ++ ++ public function render() { return <<<'HTML' ++
{{ 'a:'.$first->title }} {{ 'b:'.$second->title }}
++ HTML; } ++ }); ++ ++ MutableArticle::resolveConnection()->enableQueryLog(); ++ MutableArticle::resolveConnection()->flushQueryLog(); ++ ++ // The saved model shouldn't be reused for $second — it should fall ++ // through to a fresh query, which reads the same saved title... ++ $component->call('rename') ++ ->assertSee('a:Renamed') ++ ->assertSee('b:Renamed'); ++ ++ $selects = array_filter( ++ MutableArticle::resolveConnection()->getQueryLog(), ++ fn ($q) => str_starts_with($q['query'], 'select'), ++ ); ++ ++ $this->assertCount(2, $selects); ++ } ++ ++ public function test_a_model_saved_after_its_reuse_was_rejected_is_not_served_stale() ++ { ++ if (PHP_VERSION_ID < 80400) $this->markTestSkipped('Requires lazy model proxies'); ++ ++ $this->resetMutableArticles(); ++ ++ Livewire::test(new class extends \Livewire\Component { ++ public MutableArticle $first; ++ ++ public MutableArticle $second; ++ ++ public Collection $articles; ++ ++ public function mount() { ++ $this->first = MutableArticle::find(1); ++ $this->second = MutableArticle::find(1); ++ $this->articles = MutableArticle::all(); ++ } ++ ++ public function rename() { ++ // Once a mutated instance is encountered, the model shouldn't be ++ // shared for the rest of the request — even after the collection ++ // resolves a clean instance while the mutation is unsaved... ++ $this->first->title = 'Renamed'; ++ ++ $this->articles->count(); ++ ++ $this->first->save(); ++ } ++ ++ public function render() { return <<<'HTML' ++
{{ 'b:'.$second->title }}
++ HTML; } ++ }) ++ ->call('rename') ++ ->assertSee('b:Renamed'); ++ } ++ ++ public function test_a_model_deleted_after_its_reuse_was_rejected_is_not_resurrected() ++ { ++ if (PHP_VERSION_ID < 80400) $this->markTestSkipped('Requires lazy model proxies'); ++ ++ $this->resetMutableArticles(); ++ ++ Livewire::test(new class extends \Livewire\Component { ++ public MutableArticle $selected; ++ ++ public Collection $articles; ++ ++ public Collection $others; ++ ++ public function mount() { ++ $this->selected = MutableArticle::find(1); ++ $this->articles = MutableArticle::all(); ++ $this->others = MutableArticle::all(); ++ } ++ ++ public function deleteSelected() { ++ $this->selected->title = 'Doomed'; ++ ++ $this->articles->count(); ++ ++ $this->selected->delete(); ++ } ++ ++ public function render() { return <<<'HTML' ++
++ @foreach($others as $article) ++ {{ $article->title.'-'.$loop->index }} ++ @endforeach ++
++ HTML; } ++ }) ++ ->call('deleteSelected') ++ ->assertDontSee('First-') ++ ->assertDontSee('Doomed-') ++ ->assertSee('Second-0'); ++ } ++ ++ protected function resetMutableArticles() ++ { ++ // Reset the table as these tests modify or delete its rows... ++ MutableArticle::query()->delete(); ++ MutableArticle::insert([ ++ ['id' => 1, 'title' => 'First'], ++ ['id' => 2, 'title' => 'Second'], ++ ]); ++ } ++ + public function test_hydrating_an_empty_eloquent_collection_does_not_trigger_deprecations() + { + $component = Livewire::test(new class extends \Livewire\Component { +@@ -384,6 +784,19 @@ class Article extends Model + ]; + } + ++// Uses its own table so modifying or deleting rows doesn't affect other tests... ++class MutableArticle extends Model ++{ ++ use Sushi; ++ ++ protected $guarded = []; ++ ++ protected $rows = [ ++ ['title' => 'First'], ++ ['title' => 'Second'], ++ ]; ++} ++ + // Simulates tightenco/parental's HasParent trait, which overrides + // getTable() and getMorphClass() to return the parent's values so + // that polymorphic relations use the parent's table. diff --git a/tasks/livewire__livewire-10633/tests/test.sh b/tasks/livewire__livewire-10633/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..f72416dff2e15ba8c6649bb1ac374c3172a0b000 --- /dev/null +++ b/tasks/livewire__livewire-10633/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace a3064d59dd5f6f5db2f7f81de78948e91551dfe7 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/livewire__livewire-10633/tests/verifier.py b/tasks/livewire__livewire-10633/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/livewire__livewire-10633/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/livewire__livewire-10637/environment/Dockerfile b/tasks/livewire__livewire-10637/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..391fc71bcfed7a0d3a53520d976af34f834a8736 --- /dev/null +++ b/tasks/livewire__livewire-10637/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/livewire/livewire.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/livewire/livewire.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/livewire/livewire.git +WORKDIR /workspace +RUN git fetch --depth 1 origin a4c57fc1e2615745176568823a888e1a2f2d9e09 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard a4c57fc1e2615745176568823a888e1a2f2d9e09 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base a4c57fc1e2615745176568823a888e1a2f2d9e09 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/livewire__livewire-10637/instruction.md b/tasks/livewire__livewire-10637/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..19db5ecce69ceabb5ece3ca000f31010a07b429c --- /dev/null +++ b/tasks/livewire__livewire-10637/instruction.md @@ -0,0 +1,31 @@ +# Issue + +**Title:** [4.x] Reuse resolved models across properties + +## Description + +Backports #10633 from main to 4.x by cherry-pick. This avoids duplicate model queries during update hydration while retaining 4.x model synth architecture. + +Verification: +- Focused SupportModels suite: 27 tests, 64 assertions, 1 skipped + + + +## Summary by CodeRabbit + +- **Performance** + - Reduced duplicate model lookups when the same records are used across multiple properties or collections. + - Improved collection hydration by reusing records already loaded during a request. + +- **Reliability** + - Ensured updated or deleted records are not incorrectly reused. + - Preserved request isolation so cached records do not carry over between requests. + +- **Bug Fixes** + - Improved consistency when models are saved, modified, or removed during request processing. + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `a4c57fc1e261`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10637/solution/patch.diff b/tasks/livewire__livewire-10637/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..2276ea9c7fdaabe5d34a0859f63fe075baab7ec8 --- /dev/null +++ b/tasks/livewire__livewire-10637/solution/patch.diff @@ -0,0 +1,593 @@ +diff --git a/src/Features/SupportModels/EloquentCollectionSynth.php b/src/Features/SupportModels/EloquentCollectionSynth.php +index 18bdfa2b..732214b3 100644 +--- a/src/Features/SupportModels/EloquentCollectionSynth.php ++++ b/src/Features/SupportModels/EloquentCollectionSynth.php +@@ -76,16 +76,36 @@ class EloquentCollectionSynth extends Synth { + } + + return $this->makeLazyProxy($class, $meta, function () use ($modelClass, $keys, $meta) { +- // We are using Laravel's method here for restoring the collection, which ensures +- // that all models in the collection are restored in one query, preventing n+1 +- // issues and also only restores models that exist. +- $collection = (new $modelClass)->newQueryForRestoration($keys)->useWritePdo()->get(); +- +- $collection = $collection->keyBy->getKey(); ++ $models = []; ++ $missingKeys = []; ++ ++ // Reuse any models already resolved this request — by route binding (via ++ // SubstituteBindings middleware) or by another hydrated property — so ++ // that only the remaining models need to be queried. ++ foreach (array_unique($keys) as $key) { ++ if ($model = SupportModels::getResolvedModel($modelClass, $key)) { ++ $models[$key] = $model; ++ } else { ++ $missingKeys[] = $key; ++ } ++ } ++ ++ if (count($missingKeys) > 0) { ++ // We are using Laravel's method here for restoring the collection, which ensures ++ // that all models in the collection are restored in one query, preventing n+1 ++ // issues and also only restores models that exist. ++ $collection = (new $modelClass)->newQueryForRestoration($missingKeys)->useWritePdo()->get(); ++ ++ foreach ($collection as $model) { ++ $models[$model->getKey()] = $model; ++ ++ SupportModels::rememberResolvedModel($model); ++ } ++ } + + return new $meta['class']( +- collect($meta['keys'])->map(function ($id) use ($collection) { +- return $collection[$id] ?? null; ++ collect($meta['keys'])->map(function ($id) use ($models) { ++ return $models[$id] ?? null; + })->filter() + ); + }); +diff --git a/src/Features/SupportModels/ModelSynth.php b/src/Features/SupportModels/ModelSynth.php +index 0232d750..6d92cc45 100644 +--- a/src/Features/SupportModels/ModelSynth.php ++++ b/src/Features/SupportModels/ModelSynth.php +@@ -4,7 +4,6 @@ namespace Livewire\Features\SupportModels; + + use Livewire\Mechanisms\HandleComponents\Synthesizers\Synth; + use Livewire\Mechanisms\HandleComponents\ComponentContext; +-use Livewire\Mechanisms\PersistentMiddleware\PersistentMiddleware; + use Illuminate\Queue\SerializesAndRestoresModelIdentifiers; + use Illuminate\Database\Eloquent\Relations\Relation; + use Illuminate\Database\Eloquent\Model; +@@ -74,16 +73,29 @@ class ModelSynth extends Synth { + + $key = $meta['key']; + +- // If this model was already resolved by route binding (via +- // SubstituteBindings middleware), reuse it to avoid a duplicate query. +- $resolvedModel = app(PersistentMiddleware::class)->getResolvedRouteModel($class, $key); ++ // If this model was already resolved this request — by route binding (via ++ // SubstituteBindings middleware) or by another hydrated property — then ++ // reuse it to avoid a duplicate query. ++ $resolvedModel = SupportModels::getResolvedModel($class, $key); + + if ($resolvedModel) { + return $resolvedModel; + } + + return $this->makeLazyProxy($class, $meta, function () use ($class, $key) { +- return (new $class)->newQueryForRestoration($key)->useWritePdo()->firstOrFail(); ++ // Another property (like a collection containing this model) may have ++ // resolved since hydration, so check for a match one more time... ++ $resolvedModel = SupportModels::getResolvedModel($class, $key); ++ ++ if ($resolvedModel) { ++ return $resolvedModel; ++ } ++ ++ $model = (new $class)->newQueryForRestoration($key)->useWritePdo()->firstOrFail(); ++ ++ SupportModels::rememberResolvedModel($model); ++ ++ return $model; + }); + } + +diff --git a/src/Features/SupportModels/SupportModels.php b/src/Features/SupportModels/SupportModels.php +index 7a8b1691..afc9e89c 100644 +--- a/src/Features/SupportModels/SupportModels.php ++++ b/src/Features/SupportModels/SupportModels.php +@@ -2,15 +2,62 @@ + + namespace Livewire\Features\SupportModels; + ++use function Livewire\on; ++use Livewire\Mechanisms\PersistentMiddleware\PersistentMiddleware; + use Livewire\ComponentHook; + + class SupportModels extends ComponentHook + { ++ public static $resolvedModels = []; ++ ++ public static $staleModels = []; ++ + static function provide() + { + app('livewire')->propertySynthesizer([ + ModelSynth::class, + EloquentCollectionSynth::class, + ]); ++ ++ on('flush-state', function () { ++ static::$resolvedModels = []; ++ static::$staleModels = []; ++ }); ++ } ++ ++ static function rememberResolvedModel($model) ++ { ++ $hash = get_class($model).':'.$model->getKey(); ++ ++ // Don't track models that have gone stale, otherwise a deletion or an ++ // update made through the original instance couldn't be detected... ++ if (isset(static::$staleModels[$hash])) return; ++ ++ static::$resolvedModels[$hash] = $model; ++ } ++ ++ static function getResolvedModel($class, $key) ++ { ++ $hash = $class.':'.$key; ++ ++ if (isset(static::$staleModels[$hash])) return null; ++ ++ $model = static::$resolvedModels[$hash] ++ ?? app(PersistentMiddleware::class)->getResolvedRouteModel($class, $key); ++ ++ if (! $model) return null; ++ ++ // Only reuse an instance that is indistinguishable from a freshly queried ++ // one. Once an instance has been deleted or mutated, stop sharing that ++ // model for the rest of the request and fall back to fresh queries... ++ if (! $model->exists || $model->isDirty() || $model->wasChanged()) { ++ static::$staleModels[$hash] = true; ++ ++ unset(static::$resolvedModels[$hash]); ++ ++ return null; ++ } ++ ++ return $model; + } + } +diff --git a/src/Features/SupportModels/UnitTest.php b/src/Features/SupportModels/UnitTest.php +index 76a9072c..e025938b 100644 +--- a/src/Features/SupportModels/UnitTest.php ++++ b/src/Features/SupportModels/UnitTest.php +@@ -325,6 +325,406 @@ class UnitTest extends \Tests\TestCase + $this->assertCount(1, array_values($articleQueries)); + } + ++ public function test_a_model_property_reuses_a_model_already_hydrated_by_a_collection_property() ++ { ++ $component = Livewire::test(new class extends \Livewire\Component { ++ public Collection $articles; ++ ++ public Article $selected; ++ ++ public function mount() { ++ $this->articles = Article::all(); ++ $this->selected = $this->articles->first(); ++ } ++ ++ public function render() { return <<<'HTML' ++
++ @foreach($articles as $article) ++ {{ $article->title.'-'.$loop->index }} ++ @endforeach ++ {{ 'Selected: '.$selected->title }} ++
++ HTML; } ++ }); ++ ++ Article::resolveConnection()->enableQueryLog(); ++ Article::resolveConnection()->flushQueryLog(); ++ ++ $component->call('$refresh') ++ ->assertSee('First-0') ++ ->assertSee('Second-1') ++ ->assertSee('Selected: First'); ++ ++ $this->assertCount(1, Article::resolveConnection()->getQueryLog()); ++ } ++ ++ public function test_a_collection_property_only_queries_models_not_already_hydrated_by_a_model_property() ++ { ++ $component = Livewire::test(new class extends \Livewire\Component { ++ public Article $selected; ++ ++ public Collection $articles; ++ ++ public function mount() { ++ $this->selected = Article::first(); ++ $this->articles = Article::all(); ++ } ++ ++ public function render() { return <<<'HTML' ++
++ {{ 'Selected: '.$selected->title }} ++ @foreach($articles as $article) ++ {{ $article->title.'-'.$loop->index }} ++ @endforeach ++
++ HTML; } ++ }); ++ ++ Article::resolveConnection()->enableQueryLog(); ++ Article::resolveConnection()->flushQueryLog(); ++ ++ $component->call('$refresh') ++ ->assertSee('Selected: First') ++ ->assertSee('First-0') ++ ->assertSee('Second-1'); ++ ++ $queryLog = Article::resolveConnection()->getQueryLog(); ++ ++ $this->assertCount(2, $queryLog); ++ ++ // The collection query should only restore the model that wasn't already ++ // resolved by the model property. Integer keys may be inlined into the ++ // SQL or passed as bindings depending on the Laravel version... ++ [$modelQuery, $collectionQuery] = $queryLog; ++ ++ $this->assertTrue( ++ str_contains($collectionQuery['query'], 'in (2)') || $collectionQuery['bindings'] === [2], ++ 'The collection should only have queried for the unresolved model', ++ ); ++ } ++ ++ public function test_two_model_properties_with_the_same_key_are_hydrated_with_one_query() ++ { ++ $component = Livewire::test(new class extends \Livewire\Component { ++ public Article $first; ++ ++ public Article $second; ++ ++ public function mount() { ++ $this->first = Article::first(); ++ $this->second = Article::first(); ++ } ++ ++ public function render() { return <<<'HTML' ++
{{ 'a:'.$first->title }} {{ 'b:'.$second->title }}
++ HTML; } ++ }); ++ ++ Article::resolveConnection()->enableQueryLog(); ++ Article::resolveConnection()->flushQueryLog(); ++ ++ $component->call('$refresh') ++ ->assertSee('a:First') ++ ->assertSee('b:First'); ++ ++ $this->assertCount(1, Article::resolveConnection()->getQueryLog()); ++ } ++ ++ public function test_reused_model_instances_are_shared_within_a_request() ++ { ++ Livewire::test(new class extends \Livewire\Component { ++ public Collection $articles; ++ ++ public Article $selected; ++ ++ public function mount() { ++ $this->articles = Article::all(); ++ $this->selected = $this->articles->first(); ++ } ++ ++ public function rename() { ++ $this->articles->count(); ++ ++ $this->selected->title = 'Renamed'; ++ } ++ ++ public function render() { return <<<'HTML' ++
++ @foreach($articles as $article) ++ {{ $article->title.'-'.$loop->index }} ++ @endforeach ++
++ HTML; } ++ }) ++ ->call('rename') ++ ->assertSee('Renamed-0') ++ ->assertSee('Second-1'); ++ } ++ ++ public function test_a_collection_is_not_queried_when_all_its_models_are_already_resolved() ++ { ++ $component = Livewire::test(new class extends \Livewire\Component { ++ public Article $one; ++ ++ public Article $two; ++ ++ public Collection $articles; ++ ++ public function mount() { ++ $this->one = Article::find(1); ++ $this->two = Article::find(2); ++ $this->articles = new Collection([Article::find(1), Article::find(1), Article::find(2)]); ++ } ++ ++ public function render() { return <<<'HTML' ++
++ {{ 'a:'.$one->title }} {{ 'b:'.$two->title }} ++ @foreach($articles as $article) ++ {{ $article->title.'-'.$loop->index }} ++ @endforeach ++
++ HTML; } ++ }); ++ ++ Article::resolveConnection()->enableQueryLog(); ++ Article::resolveConnection()->flushQueryLog(); ++ ++ $component->call('$refresh') ++ ->assertSee('a:First') ++ ->assertSee('b:Second') ++ ->assertSee('First-0') ++ ->assertSee('First-1') ++ ->assertSee('Second-2'); ++ ++ $this->assertCount(2, Article::resolveConnection()->getQueryLog()); ++ } ++ ++ public function test_resolved_models_are_not_reused_across_requests() ++ { ++ $component = Livewire::test(new class extends \Livewire\Component { ++ public Article $article; ++ ++ public function mount() { ++ $this->article = Article::first(); ++ } ++ ++ public function render() { return <<<'HTML' ++
{{ $article->title }}
++ HTML; } ++ }); ++ ++ Article::resolveConnection()->enableQueryLog(); ++ Article::resolveConnection()->flushQueryLog(); ++ ++ $component->call('$refresh')->assertSee('First'); ++ $component->call('$refresh')->assertSee('First'); ++ ++ $this->assertCount(2, Article::resolveConnection()->getQueryLog()); ++ } ++ ++ public function test_a_mutated_model_is_not_reused_by_other_properties() ++ { ++ // On earlier versions there are no lazy proxies, so properties hydrate ++ // eagerly before any mutations and share the still-clean instance... ++ if (PHP_VERSION_ID < 80400) $this->markTestSkipped('Requires lazy model proxies'); ++ ++ $component = Livewire::test(new class extends \Livewire\Component { ++ public Article $first; ++ ++ public Article $second; ++ ++ public function mount() { ++ $this->first = Article::first(); ++ $this->second = Article::first(); ++ } ++ ++ public function rename() { ++ $this->first->title = 'Draft'; ++ } ++ ++ public function render() { return <<<'HTML' ++
{{ 'a:'.$first->title }} {{ 'b:'.$second->title }}
++ HTML; } ++ }); ++ ++ Article::resolveConnection()->enableQueryLog(); ++ Article::resolveConnection()->flushQueryLog(); ++ ++ // The unsaved mutation on $first shouldn't leak into $second — it ++ // should fall through to a fresh query instead... ++ $component->call('rename') ++ ->assertSee('a:Draft') ++ ->assertSee('b:First'); ++ ++ $this->assertCount(2, Article::resolveConnection()->getQueryLog()); ++ } ++ ++ public function test_a_deleted_model_is_not_reused_when_hydrating_a_collection() ++ { ++ // On earlier versions there are no lazy proxies, so the collection is ++ // hydrated eagerly before the deletion, like it is on main... ++ if (PHP_VERSION_ID < 80400) $this->markTestSkipped('Requires lazy model proxies'); ++ ++ $this->resetMutableArticles(); ++ ++ Livewire::test(new class extends \Livewire\Component { ++ public Collection $articles; ++ ++ public MutableArticle $selected; ++ ++ public function mount() { ++ $this->articles = MutableArticle::all(); ++ $this->selected = $this->articles->first(); ++ } ++ ++ public function deleteSelected() { ++ $this->selected->delete(); ++ } ++ ++ public function render() { return <<<'HTML' ++
++ @foreach($articles as $article) ++ {{ $article->title.'-'.$loop->index }} ++ @endforeach ++
++ HTML; } ++ }) ++ ->call('deleteSelected') ++ ->assertDontSee('First-') ++ ->assertSee('Second-0'); ++ } ++ ++ public function test_a_saved_model_is_not_reused_by_other_properties() ++ { ++ if (PHP_VERSION_ID < 80400) $this->markTestSkipped('Requires lazy model proxies'); ++ ++ $this->resetMutableArticles(); ++ ++ $component = Livewire::test(new class extends \Livewire\Component { ++ public MutableArticle $first; ++ ++ public MutableArticle $second; ++ ++ public function mount() { ++ $this->first = MutableArticle::find(1); ++ $this->second = MutableArticle::find(1); ++ } ++ ++ public function rename() { ++ $this->first->update(['title' => 'Renamed']); ++ } ++ ++ public function render() { return <<<'HTML' ++
{{ 'a:'.$first->title }} {{ 'b:'.$second->title }}
++ HTML; } ++ }); ++ ++ MutableArticle::resolveConnection()->enableQueryLog(); ++ MutableArticle::resolveConnection()->flushQueryLog(); ++ ++ // The saved model shouldn't be reused for $second — it should fall ++ // through to a fresh query, which reads the same saved title... ++ $component->call('rename') ++ ->assertSee('a:Renamed') ++ ->assertSee('b:Renamed'); ++ ++ $selects = array_filter( ++ MutableArticle::resolveConnection()->getQueryLog(), ++ fn ($q) => str_starts_with($q['query'], 'select'), ++ ); ++ ++ $this->assertCount(2, $selects); ++ } ++ ++ public function test_a_model_saved_after_its_reuse_was_rejected_is_not_served_stale() ++ { ++ if (PHP_VERSION_ID < 80400) $this->markTestSkipped('Requires lazy model proxies'); ++ ++ $this->resetMutableArticles(); ++ ++ Livewire::test(new class extends \Livewire\Component { ++ public MutableArticle $first; ++ ++ public MutableArticle $second; ++ ++ public Collection $articles; ++ ++ public function mount() { ++ $this->first = MutableArticle::find(1); ++ $this->second = MutableArticle::find(1); ++ $this->articles = MutableArticle::all(); ++ } ++ ++ public function rename() { ++ // Once a mutated instance is encountered, the model shouldn't be ++ // shared for the rest of the request — even after the collection ++ // resolves a clean instance while the mutation is unsaved... ++ $this->first->title = 'Renamed'; ++ ++ $this->articles->count(); ++ ++ $this->first->save(); ++ } ++ ++ public function render() { return <<<'HTML' ++
{{ 'b:'.$second->title }}
++ HTML; } ++ }) ++ ->call('rename') ++ ->assertSee('b:Renamed'); ++ } ++ ++ public function test_a_model_deleted_after_its_reuse_was_rejected_is_not_resurrected() ++ { ++ if (PHP_VERSION_ID < 80400) $this->markTestSkipped('Requires lazy model proxies'); ++ ++ $this->resetMutableArticles(); ++ ++ Livewire::test(new class extends \Livewire\Component { ++ public MutableArticle $selected; ++ ++ public Collection $articles; ++ ++ public Collection $others; ++ ++ public function mount() { ++ $this->selected = MutableArticle::find(1); ++ $this->articles = MutableArticle::all(); ++ $this->others = MutableArticle::all(); ++ } ++ ++ public function deleteSelected() { ++ $this->selected->title = 'Doomed'; ++ ++ $this->articles->count(); ++ ++ $this->selected->delete(); ++ } ++ ++ public function render() { return <<<'HTML' ++
++ @foreach($others as $article) ++ {{ $article->title.'-'.$loop->index }} ++ @endforeach ++
++ HTML; } ++ }) ++ ->call('deleteSelected') ++ ->assertDontSee('First-') ++ ->assertDontSee('Doomed-') ++ ->assertSee('Second-0'); ++ } ++ ++ protected function resetMutableArticles() ++ { ++ // Reset the table as these tests modify or delete its rows... ++ MutableArticle::query()->delete(); ++ MutableArticle::insert([ ++ ['id' => 1, 'title' => 'First'], ++ ['id' => 2, 'title' => 'Second'], ++ ]); ++ } ++ + public function test_hydrating_an_empty_eloquent_collection_does_not_trigger_deprecations() + { + $component = Livewire::test(new class extends \Livewire\Component { +@@ -384,6 +784,19 @@ class Article extends Model + ]; + } + ++// Uses its own table so modifying or deleting rows doesn't affect other tests... ++class MutableArticle extends Model ++{ ++ use Sushi; ++ ++ protected $guarded = []; ++ ++ protected $rows = [ ++ ['title' => 'First'], ++ ['title' => 'Second'], ++ ]; ++} ++ + // Simulates tightenco/parental's HasParent trait, which overrides + // getTable() and getMorphClass() to return the parent's values so + // that polymorphic relations use the parent's table. diff --git a/tasks/livewire__livewire-10637/solution/solve.sh b/tasks/livewire__livewire-10637/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/livewire__livewire-10637/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/livewire__livewire-10637/task.toml b/tasks/livewire__livewire-10637/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ff73a49d3e5f9acdaee25b38e6fabd756a13c04f --- /dev/null +++ b/tasks/livewire__livewire-10637/task.toml @@ -0,0 +1,71 @@ +version = "1.0" + +[task] +name = "trending/livewire__livewire-10637" +description = "[4.x] Reuse resolved models across properties" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "livewire", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "livewire/livewire" +ref = "a4c57fc1e2615745176568823a888e1a2f2d9e09" +reference = "https://github.com/livewire/livewire/pull/10637" +source_access = "auto" +built_at = "2026-11-16T16:09:51.528736+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:6d07a5b500c811905e51db272a51c83dd9c3b7dd6bfe0486ab42e9e8997f6c36" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-08-31T14:13:31Z" +diff_format = "unified" +context_files = [ + "src/Features/SupportModels/EloquentCollectionSynth.php", + "src/Features/SupportModels/ModelSynth.php", + "src/Features/SupportModels/SupportModels.php", + "src/Features/SupportModels/UnitTest.php", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 518 +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.368852+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:0f13c76f3d39a5d869c4b9192fc4f13e7ad867066f7174791f5a81b4e4e5f54a" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/livewire__livewire-10637/tests/capture.py b/tasks/livewire__livewire-10637/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/livewire__livewire-10637/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/livewire__livewire-10637/tests/instruction.md b/tasks/livewire__livewire-10637/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..19db5ecce69ceabb5ece3ca000f31010a07b429c --- /dev/null +++ b/tasks/livewire__livewire-10637/tests/instruction.md @@ -0,0 +1,31 @@ +# Issue + +**Title:** [4.x] Reuse resolved models across properties + +## Description + +Backports #10633 from main to 4.x by cherry-pick. This avoids duplicate model queries during update hydration while retaining 4.x model synth architecture. + +Verification: +- Focused SupportModels suite: 27 tests, 64 assertions, 1 skipped + + + +## Summary by CodeRabbit + +- **Performance** + - Reduced duplicate model lookups when the same records are used across multiple properties or collections. + - Improved collection hydration by reusing records already loaded during a request. + +- **Reliability** + - Ensured updated or deleted records are not incorrectly reused. + - Preserved request isolation so cached records do not carry over between requests. + +- **Bug Fixes** + - Improved consistency when models are saved, modified, or removed during request processing. + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `a4c57fc1e261`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10637/tests/oracle.patch b/tasks/livewire__livewire-10637/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..2276ea9c7fdaabe5d34a0859f63fe075baab7ec8 --- /dev/null +++ b/tasks/livewire__livewire-10637/tests/oracle.patch @@ -0,0 +1,593 @@ +diff --git a/src/Features/SupportModels/EloquentCollectionSynth.php b/src/Features/SupportModels/EloquentCollectionSynth.php +index 18bdfa2b..732214b3 100644 +--- a/src/Features/SupportModels/EloquentCollectionSynth.php ++++ b/src/Features/SupportModels/EloquentCollectionSynth.php +@@ -76,16 +76,36 @@ class EloquentCollectionSynth extends Synth { + } + + return $this->makeLazyProxy($class, $meta, function () use ($modelClass, $keys, $meta) { +- // We are using Laravel's method here for restoring the collection, which ensures +- // that all models in the collection are restored in one query, preventing n+1 +- // issues and also only restores models that exist. +- $collection = (new $modelClass)->newQueryForRestoration($keys)->useWritePdo()->get(); +- +- $collection = $collection->keyBy->getKey(); ++ $models = []; ++ $missingKeys = []; ++ ++ // Reuse any models already resolved this request — by route binding (via ++ // SubstituteBindings middleware) or by another hydrated property — so ++ // that only the remaining models need to be queried. ++ foreach (array_unique($keys) as $key) { ++ if ($model = SupportModels::getResolvedModel($modelClass, $key)) { ++ $models[$key] = $model; ++ } else { ++ $missingKeys[] = $key; ++ } ++ } ++ ++ if (count($missingKeys) > 0) { ++ // We are using Laravel's method here for restoring the collection, which ensures ++ // that all models in the collection are restored in one query, preventing n+1 ++ // issues and also only restores models that exist. ++ $collection = (new $modelClass)->newQueryForRestoration($missingKeys)->useWritePdo()->get(); ++ ++ foreach ($collection as $model) { ++ $models[$model->getKey()] = $model; ++ ++ SupportModels::rememberResolvedModel($model); ++ } ++ } + + return new $meta['class']( +- collect($meta['keys'])->map(function ($id) use ($collection) { +- return $collection[$id] ?? null; ++ collect($meta['keys'])->map(function ($id) use ($models) { ++ return $models[$id] ?? null; + })->filter() + ); + }); +diff --git a/src/Features/SupportModels/ModelSynth.php b/src/Features/SupportModels/ModelSynth.php +index 0232d750..6d92cc45 100644 +--- a/src/Features/SupportModels/ModelSynth.php ++++ b/src/Features/SupportModels/ModelSynth.php +@@ -4,7 +4,6 @@ namespace Livewire\Features\SupportModels; + + use Livewire\Mechanisms\HandleComponents\Synthesizers\Synth; + use Livewire\Mechanisms\HandleComponents\ComponentContext; +-use Livewire\Mechanisms\PersistentMiddleware\PersistentMiddleware; + use Illuminate\Queue\SerializesAndRestoresModelIdentifiers; + use Illuminate\Database\Eloquent\Relations\Relation; + use Illuminate\Database\Eloquent\Model; +@@ -74,16 +73,29 @@ class ModelSynth extends Synth { + + $key = $meta['key']; + +- // If this model was already resolved by route binding (via +- // SubstituteBindings middleware), reuse it to avoid a duplicate query. +- $resolvedModel = app(PersistentMiddleware::class)->getResolvedRouteModel($class, $key); ++ // If this model was already resolved this request — by route binding (via ++ // SubstituteBindings middleware) or by another hydrated property — then ++ // reuse it to avoid a duplicate query. ++ $resolvedModel = SupportModels::getResolvedModel($class, $key); + + if ($resolvedModel) { + return $resolvedModel; + } + + return $this->makeLazyProxy($class, $meta, function () use ($class, $key) { +- return (new $class)->newQueryForRestoration($key)->useWritePdo()->firstOrFail(); ++ // Another property (like a collection containing this model) may have ++ // resolved since hydration, so check for a match one more time... ++ $resolvedModel = SupportModels::getResolvedModel($class, $key); ++ ++ if ($resolvedModel) { ++ return $resolvedModel; ++ } ++ ++ $model = (new $class)->newQueryForRestoration($key)->useWritePdo()->firstOrFail(); ++ ++ SupportModels::rememberResolvedModel($model); ++ ++ return $model; + }); + } + +diff --git a/src/Features/SupportModels/SupportModels.php b/src/Features/SupportModels/SupportModels.php +index 7a8b1691..afc9e89c 100644 +--- a/src/Features/SupportModels/SupportModels.php ++++ b/src/Features/SupportModels/SupportModels.php +@@ -2,15 +2,62 @@ + + namespace Livewire\Features\SupportModels; + ++use function Livewire\on; ++use Livewire\Mechanisms\PersistentMiddleware\PersistentMiddleware; + use Livewire\ComponentHook; + + class SupportModels extends ComponentHook + { ++ public static $resolvedModels = []; ++ ++ public static $staleModels = []; ++ + static function provide() + { + app('livewire')->propertySynthesizer([ + ModelSynth::class, + EloquentCollectionSynth::class, + ]); ++ ++ on('flush-state', function () { ++ static::$resolvedModels = []; ++ static::$staleModels = []; ++ }); ++ } ++ ++ static function rememberResolvedModel($model) ++ { ++ $hash = get_class($model).':'.$model->getKey(); ++ ++ // Don't track models that have gone stale, otherwise a deletion or an ++ // update made through the original instance couldn't be detected... ++ if (isset(static::$staleModels[$hash])) return; ++ ++ static::$resolvedModels[$hash] = $model; ++ } ++ ++ static function getResolvedModel($class, $key) ++ { ++ $hash = $class.':'.$key; ++ ++ if (isset(static::$staleModels[$hash])) return null; ++ ++ $model = static::$resolvedModels[$hash] ++ ?? app(PersistentMiddleware::class)->getResolvedRouteModel($class, $key); ++ ++ if (! $model) return null; ++ ++ // Only reuse an instance that is indistinguishable from a freshly queried ++ // one. Once an instance has been deleted or mutated, stop sharing that ++ // model for the rest of the request and fall back to fresh queries... ++ if (! $model->exists || $model->isDirty() || $model->wasChanged()) { ++ static::$staleModels[$hash] = true; ++ ++ unset(static::$resolvedModels[$hash]); ++ ++ return null; ++ } ++ ++ return $model; + } + } +diff --git a/src/Features/SupportModels/UnitTest.php b/src/Features/SupportModels/UnitTest.php +index 76a9072c..e025938b 100644 +--- a/src/Features/SupportModels/UnitTest.php ++++ b/src/Features/SupportModels/UnitTest.php +@@ -325,6 +325,406 @@ class UnitTest extends \Tests\TestCase + $this->assertCount(1, array_values($articleQueries)); + } + ++ public function test_a_model_property_reuses_a_model_already_hydrated_by_a_collection_property() ++ { ++ $component = Livewire::test(new class extends \Livewire\Component { ++ public Collection $articles; ++ ++ public Article $selected; ++ ++ public function mount() { ++ $this->articles = Article::all(); ++ $this->selected = $this->articles->first(); ++ } ++ ++ public function render() { return <<<'HTML' ++
++ @foreach($articles as $article) ++ {{ $article->title.'-'.$loop->index }} ++ @endforeach ++ {{ 'Selected: '.$selected->title }} ++
++ HTML; } ++ }); ++ ++ Article::resolveConnection()->enableQueryLog(); ++ Article::resolveConnection()->flushQueryLog(); ++ ++ $component->call('$refresh') ++ ->assertSee('First-0') ++ ->assertSee('Second-1') ++ ->assertSee('Selected: First'); ++ ++ $this->assertCount(1, Article::resolveConnection()->getQueryLog()); ++ } ++ ++ public function test_a_collection_property_only_queries_models_not_already_hydrated_by_a_model_property() ++ { ++ $component = Livewire::test(new class extends \Livewire\Component { ++ public Article $selected; ++ ++ public Collection $articles; ++ ++ public function mount() { ++ $this->selected = Article::first(); ++ $this->articles = Article::all(); ++ } ++ ++ public function render() { return <<<'HTML' ++
++ {{ 'Selected: '.$selected->title }} ++ @foreach($articles as $article) ++ {{ $article->title.'-'.$loop->index }} ++ @endforeach ++
++ HTML; } ++ }); ++ ++ Article::resolveConnection()->enableQueryLog(); ++ Article::resolveConnection()->flushQueryLog(); ++ ++ $component->call('$refresh') ++ ->assertSee('Selected: First') ++ ->assertSee('First-0') ++ ->assertSee('Second-1'); ++ ++ $queryLog = Article::resolveConnection()->getQueryLog(); ++ ++ $this->assertCount(2, $queryLog); ++ ++ // The collection query should only restore the model that wasn't already ++ // resolved by the model property. Integer keys may be inlined into the ++ // SQL or passed as bindings depending on the Laravel version... ++ [$modelQuery, $collectionQuery] = $queryLog; ++ ++ $this->assertTrue( ++ str_contains($collectionQuery['query'], 'in (2)') || $collectionQuery['bindings'] === [2], ++ 'The collection should only have queried for the unresolved model', ++ ); ++ } ++ ++ public function test_two_model_properties_with_the_same_key_are_hydrated_with_one_query() ++ { ++ $component = Livewire::test(new class extends \Livewire\Component { ++ public Article $first; ++ ++ public Article $second; ++ ++ public function mount() { ++ $this->first = Article::first(); ++ $this->second = Article::first(); ++ } ++ ++ public function render() { return <<<'HTML' ++
{{ 'a:'.$first->title }} {{ 'b:'.$second->title }}
++ HTML; } ++ }); ++ ++ Article::resolveConnection()->enableQueryLog(); ++ Article::resolveConnection()->flushQueryLog(); ++ ++ $component->call('$refresh') ++ ->assertSee('a:First') ++ ->assertSee('b:First'); ++ ++ $this->assertCount(1, Article::resolveConnection()->getQueryLog()); ++ } ++ ++ public function test_reused_model_instances_are_shared_within_a_request() ++ { ++ Livewire::test(new class extends \Livewire\Component { ++ public Collection $articles; ++ ++ public Article $selected; ++ ++ public function mount() { ++ $this->articles = Article::all(); ++ $this->selected = $this->articles->first(); ++ } ++ ++ public function rename() { ++ $this->articles->count(); ++ ++ $this->selected->title = 'Renamed'; ++ } ++ ++ public function render() { return <<<'HTML' ++
++ @foreach($articles as $article) ++ {{ $article->title.'-'.$loop->index }} ++ @endforeach ++
++ HTML; } ++ }) ++ ->call('rename') ++ ->assertSee('Renamed-0') ++ ->assertSee('Second-1'); ++ } ++ ++ public function test_a_collection_is_not_queried_when_all_its_models_are_already_resolved() ++ { ++ $component = Livewire::test(new class extends \Livewire\Component { ++ public Article $one; ++ ++ public Article $two; ++ ++ public Collection $articles; ++ ++ public function mount() { ++ $this->one = Article::find(1); ++ $this->two = Article::find(2); ++ $this->articles = new Collection([Article::find(1), Article::find(1), Article::find(2)]); ++ } ++ ++ public function render() { return <<<'HTML' ++
++ {{ 'a:'.$one->title }} {{ 'b:'.$two->title }} ++ @foreach($articles as $article) ++ {{ $article->title.'-'.$loop->index }} ++ @endforeach ++
++ HTML; } ++ }); ++ ++ Article::resolveConnection()->enableQueryLog(); ++ Article::resolveConnection()->flushQueryLog(); ++ ++ $component->call('$refresh') ++ ->assertSee('a:First') ++ ->assertSee('b:Second') ++ ->assertSee('First-0') ++ ->assertSee('First-1') ++ ->assertSee('Second-2'); ++ ++ $this->assertCount(2, Article::resolveConnection()->getQueryLog()); ++ } ++ ++ public function test_resolved_models_are_not_reused_across_requests() ++ { ++ $component = Livewire::test(new class extends \Livewire\Component { ++ public Article $article; ++ ++ public function mount() { ++ $this->article = Article::first(); ++ } ++ ++ public function render() { return <<<'HTML' ++
{{ $article->title }}
++ HTML; } ++ }); ++ ++ Article::resolveConnection()->enableQueryLog(); ++ Article::resolveConnection()->flushQueryLog(); ++ ++ $component->call('$refresh')->assertSee('First'); ++ $component->call('$refresh')->assertSee('First'); ++ ++ $this->assertCount(2, Article::resolveConnection()->getQueryLog()); ++ } ++ ++ public function test_a_mutated_model_is_not_reused_by_other_properties() ++ { ++ // On earlier versions there are no lazy proxies, so properties hydrate ++ // eagerly before any mutations and share the still-clean instance... ++ if (PHP_VERSION_ID < 80400) $this->markTestSkipped('Requires lazy model proxies'); ++ ++ $component = Livewire::test(new class extends \Livewire\Component { ++ public Article $first; ++ ++ public Article $second; ++ ++ public function mount() { ++ $this->first = Article::first(); ++ $this->second = Article::first(); ++ } ++ ++ public function rename() { ++ $this->first->title = 'Draft'; ++ } ++ ++ public function render() { return <<<'HTML' ++
{{ 'a:'.$first->title }} {{ 'b:'.$second->title }}
++ HTML; } ++ }); ++ ++ Article::resolveConnection()->enableQueryLog(); ++ Article::resolveConnection()->flushQueryLog(); ++ ++ // The unsaved mutation on $first shouldn't leak into $second — it ++ // should fall through to a fresh query instead... ++ $component->call('rename') ++ ->assertSee('a:Draft') ++ ->assertSee('b:First'); ++ ++ $this->assertCount(2, Article::resolveConnection()->getQueryLog()); ++ } ++ ++ public function test_a_deleted_model_is_not_reused_when_hydrating_a_collection() ++ { ++ // On earlier versions there are no lazy proxies, so the collection is ++ // hydrated eagerly before the deletion, like it is on main... ++ if (PHP_VERSION_ID < 80400) $this->markTestSkipped('Requires lazy model proxies'); ++ ++ $this->resetMutableArticles(); ++ ++ Livewire::test(new class extends \Livewire\Component { ++ public Collection $articles; ++ ++ public MutableArticle $selected; ++ ++ public function mount() { ++ $this->articles = MutableArticle::all(); ++ $this->selected = $this->articles->first(); ++ } ++ ++ public function deleteSelected() { ++ $this->selected->delete(); ++ } ++ ++ public function render() { return <<<'HTML' ++
++ @foreach($articles as $article) ++ {{ $article->title.'-'.$loop->index }} ++ @endforeach ++
++ HTML; } ++ }) ++ ->call('deleteSelected') ++ ->assertDontSee('First-') ++ ->assertSee('Second-0'); ++ } ++ ++ public function test_a_saved_model_is_not_reused_by_other_properties() ++ { ++ if (PHP_VERSION_ID < 80400) $this->markTestSkipped('Requires lazy model proxies'); ++ ++ $this->resetMutableArticles(); ++ ++ $component = Livewire::test(new class extends \Livewire\Component { ++ public MutableArticle $first; ++ ++ public MutableArticle $second; ++ ++ public function mount() { ++ $this->first = MutableArticle::find(1); ++ $this->second = MutableArticle::find(1); ++ } ++ ++ public function rename() { ++ $this->first->update(['title' => 'Renamed']); ++ } ++ ++ public function render() { return <<<'HTML' ++
{{ 'a:'.$first->title }} {{ 'b:'.$second->title }}
++ HTML; } ++ }); ++ ++ MutableArticle::resolveConnection()->enableQueryLog(); ++ MutableArticle::resolveConnection()->flushQueryLog(); ++ ++ // The saved model shouldn't be reused for $second — it should fall ++ // through to a fresh query, which reads the same saved title... ++ $component->call('rename') ++ ->assertSee('a:Renamed') ++ ->assertSee('b:Renamed'); ++ ++ $selects = array_filter( ++ MutableArticle::resolveConnection()->getQueryLog(), ++ fn ($q) => str_starts_with($q['query'], 'select'), ++ ); ++ ++ $this->assertCount(2, $selects); ++ } ++ ++ public function test_a_model_saved_after_its_reuse_was_rejected_is_not_served_stale() ++ { ++ if (PHP_VERSION_ID < 80400) $this->markTestSkipped('Requires lazy model proxies'); ++ ++ $this->resetMutableArticles(); ++ ++ Livewire::test(new class extends \Livewire\Component { ++ public MutableArticle $first; ++ ++ public MutableArticle $second; ++ ++ public Collection $articles; ++ ++ public function mount() { ++ $this->first = MutableArticle::find(1); ++ $this->second = MutableArticle::find(1); ++ $this->articles = MutableArticle::all(); ++ } ++ ++ public function rename() { ++ // Once a mutated instance is encountered, the model shouldn't be ++ // shared for the rest of the request — even after the collection ++ // resolves a clean instance while the mutation is unsaved... ++ $this->first->title = 'Renamed'; ++ ++ $this->articles->count(); ++ ++ $this->first->save(); ++ } ++ ++ public function render() { return <<<'HTML' ++
{{ 'b:'.$second->title }}
++ HTML; } ++ }) ++ ->call('rename') ++ ->assertSee('b:Renamed'); ++ } ++ ++ public function test_a_model_deleted_after_its_reuse_was_rejected_is_not_resurrected() ++ { ++ if (PHP_VERSION_ID < 80400) $this->markTestSkipped('Requires lazy model proxies'); ++ ++ $this->resetMutableArticles(); ++ ++ Livewire::test(new class extends \Livewire\Component { ++ public MutableArticle $selected; ++ ++ public Collection $articles; ++ ++ public Collection $others; ++ ++ public function mount() { ++ $this->selected = MutableArticle::find(1); ++ $this->articles = MutableArticle::all(); ++ $this->others = MutableArticle::all(); ++ } ++ ++ public function deleteSelected() { ++ $this->selected->title = 'Doomed'; ++ ++ $this->articles->count(); ++ ++ $this->selected->delete(); ++ } ++ ++ public function render() { return <<<'HTML' ++
++ @foreach($others as $article) ++ {{ $article->title.'-'.$loop->index }} ++ @endforeach ++
++ HTML; } ++ }) ++ ->call('deleteSelected') ++ ->assertDontSee('First-') ++ ->assertDontSee('Doomed-') ++ ->assertSee('Second-0'); ++ } ++ ++ protected function resetMutableArticles() ++ { ++ // Reset the table as these tests modify or delete its rows... ++ MutableArticle::query()->delete(); ++ MutableArticle::insert([ ++ ['id' => 1, 'title' => 'First'], ++ ['id' => 2, 'title' => 'Second'], ++ ]); ++ } ++ + public function test_hydrating_an_empty_eloquent_collection_does_not_trigger_deprecations() + { + $component = Livewire::test(new class extends \Livewire\Component { +@@ -384,6 +784,19 @@ class Article extends Model + ]; + } + ++// Uses its own table so modifying or deleting rows doesn't affect other tests... ++class MutableArticle extends Model ++{ ++ use Sushi; ++ ++ protected $guarded = []; ++ ++ protected $rows = [ ++ ['title' => 'First'], ++ ['title' => 'Second'], ++ ]; ++} ++ + // Simulates tightenco/parental's HasParent trait, which overrides + // getTable() and getMorphClass() to return the parent's values so + // that polymorphic relations use the parent's table. diff --git a/tasks/livewire__livewire-10637/tests/test.sh b/tasks/livewire__livewire-10637/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..a3edb3ffa138c4a7d0ec2ee97b82c6257c2fb8d5 --- /dev/null +++ b/tasks/livewire__livewire-10637/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace a4c57fc1e2615745176568823a888e1a2f2d9e09 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/livewire__livewire-10637/tests/verifier.py b/tasks/livewire__livewire-10637/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/livewire__livewire-10637/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/livewire__livewire-10638/environment/Dockerfile b/tasks/livewire__livewire-10638/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c6c9672185ae62a024edd04791b8c8f4aa972cfc --- /dev/null +++ b/tasks/livewire__livewire-10638/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/livewire/livewire.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/livewire/livewire.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/livewire/livewire.git +WORKDIR /workspace +RUN git fetch --depth 1 origin c755844923630a921f8bea185e75771fcb9b8c7c 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard c755844923630a921f8bea185e75771fcb9b8c7c \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base c755844923630a921f8bea185e75771fcb9b8c7c \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/livewire__livewire-10638/instruction.md b/tasks/livewire__livewire-10638/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..eee1f2fb6a8e5da29f0e1a00b3854b3d138eca28 --- /dev/null +++ b/tasks/livewire__livewire-10638/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** Prepare Alpine 3.17.1 on main + +## Description + +Updates main to Alpine v3.17.1 from the published npm packages. + +Verified with a clean npm install, the full JavaScript suite (164 passed, 1 skipped), and a production build. The lockfile resolves Alpine and all bundled plugins to 3.17.1. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `c75584492363`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10638/solution/patch.diff b/tasks/livewire__livewire-10638/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..64ff1cdc5e362aea25bf414e75714a82ac584462 --- /dev/null +++ b/tasks/livewire__livewire-10638/solution/patch.diff @@ -0,0 +1,185 @@ +diff --git a/package-lock.json b/package-lock.json +index 18afc3dd..9dcd46c9 100644 +--- a/package-lock.json ++++ b/package-lock.json +@@ -7,18 +7,18 @@ + "name": "laravel-livewire", + "license": "MIT", + "dependencies": { +- "@alpinejs/anchor": "^3.17.0", +- "@alpinejs/collapse": "^3.17.0", +- "@alpinejs/csp": "^3.17.0", +- "@alpinejs/focus": "^3.17.0", +- "@alpinejs/intersect": "^3.17.0", +- "@alpinejs/mask": "^3.17.0", +- "@alpinejs/morph": "^3.17.0", +- "@alpinejs/persist": "^3.17.0", +- "@alpinejs/resize": "^3.17.0", +- "@alpinejs/sort": "^3.17.0", ++ "@alpinejs/anchor": "^3.17.1", ++ "@alpinejs/collapse": "^3.17.1", ++ "@alpinejs/csp": "^3.17.1", ++ "@alpinejs/focus": "^3.17.1", ++ "@alpinejs/intersect": "^3.17.1", ++ "@alpinejs/mask": "^3.17.1", ++ "@alpinejs/morph": "^3.17.1", ++ "@alpinejs/persist": "^3.17.1", ++ "@alpinejs/resize": "^3.17.1", ++ "@alpinejs/sort": "^3.17.1", + "@vue/reactivity": "^3.2.45", +- "alpinejs": "^3.17.0", ++ "alpinejs": "^3.17.1", + "nprogress": "^0.2.0" + }, + "devDependencies": { +@@ -29,33 +29,33 @@ + } + }, + "node_modules/@alpinejs/anchor": { +- "version": "3.17.0", +- "resolved": "https://registry.npmjs.org/@alpinejs/anchor/-/anchor-3.17.0.tgz", +- "integrity": "sha512-TCY8DnyMWIWdAECjTEzBsDnh4gfiKuZq2wjmS0eHY0F38i5s4k2iOphxt5cWAytLI9yw6FKqbCytXNmjHOZjDQ==", ++ "version": "3.17.1", ++ "resolved": "https://registry.npmjs.org/@alpinejs/anchor/-/anchor-3.17.1.tgz", ++ "integrity": "sha512-x6mVH3CAUKLMMh1jEgJ7pWi9DzKEgTq6pK391wN1MvSLndjr0RYOyfCakS1Y6SqHZbTyRtwfp3zG3ECoFYILKw==", + "license": "MIT", + "dependencies": { + "@floating-ui/dom": "^1.5.3" + } + }, + "node_modules/@alpinejs/collapse": { +- "version": "3.17.0", +- "resolved": "https://registry.npmjs.org/@alpinejs/collapse/-/collapse-3.17.0.tgz", +- "integrity": "sha512-Dwjb8cEjUYdHy0FCKCfmmq/RGOotSm116w/fQBXTrX2HPw5rrJ3ZUgUhO1JOgtgkOw+vTlBERPtjJViIrMZn0w==", ++ "version": "3.17.1", ++ "resolved": "https://registry.npmjs.org/@alpinejs/collapse/-/collapse-3.17.1.tgz", ++ "integrity": "sha512-ygf0kJ2I+1TgBUjS+V1Dx2KlT/y/AatyfavzL7b2T3qrPx7WRGI4yxvFB0h6J5OZVO08dhtDTVk/Z1GIC6ME/w==", + "license": "MIT" + }, + "node_modules/@alpinejs/csp": { +- "version": "3.17.0", +- "resolved": "https://registry.npmjs.org/@alpinejs/csp/-/csp-3.17.0.tgz", +- "integrity": "sha512-D6W+RbUfkU1SyAYM0GHNF84jEHtx77HQq5CdOBvlBwDzKqbdTqjITPRLNihZ/EcUqoLgqebFzHd/v55rpP0Jhw==", ++ "version": "3.17.1", ++ "resolved": "https://registry.npmjs.org/@alpinejs/csp/-/csp-3.17.1.tgz", ++ "integrity": "sha512-HDrY0ZxvJWSmeUYqtHVSsitaqy1es3VDCNodPpdQRX4nHhHiRoeib+rOzRFFStFRD/6x0KmQzJVJ4FCLAI/DUQ==", + "license": "MIT", + "dependencies": { + "@vue/reactivity": "~3.5.40" + } + }, + "node_modules/@alpinejs/focus": { +- "version": "3.17.0", +- "resolved": "https://registry.npmjs.org/@alpinejs/focus/-/focus-3.17.0.tgz", +- "integrity": "sha512-tqkE2Pj4WgSXXujs3eCLxiS2ZODgNcDsKvG5lCZKlDozeRO6WFeSAjV5EKi4p+BFNIwm1937O4xwuV7hQ0Q+jA==", ++ "version": "3.17.1", ++ "resolved": "https://registry.npmjs.org/@alpinejs/focus/-/focus-3.17.1.tgz", ++ "integrity": "sha512-23+9xUfPMhuqIm6xeqLQmQTBjNY/yHtJ5np05WrFZLdKXOXCLktpAE7ZAgmPoD/s7F2banEiJzTSFDO6GnWUIg==", + "license": "MIT", + "dependencies": { + "focus-trap": "^8.0.0", +@@ -63,39 +63,39 @@ + } + }, + "node_modules/@alpinejs/intersect": { +- "version": "3.17.0", +- "resolved": "https://registry.npmjs.org/@alpinejs/intersect/-/intersect-3.17.0.tgz", +- "integrity": "sha512-6vvZFWmPo/+Vu+vSWjKkE2KFw7HF4SLS8TaGZqnLXhrwOc3UOoYdjz798lQSYhNp1W1Z0+s/Boi4kAczt5BOkA==", ++ "version": "3.17.1", ++ "resolved": "https://registry.npmjs.org/@alpinejs/intersect/-/intersect-3.17.1.tgz", ++ "integrity": "sha512-60UZyk6BNGocHgEvKxBfgqPXq9Y1tuQ363/FjdlXc1eNI8Q0arelStWLhEyd0u8JJp7FTr50S/CmaYXMijTQYQ==", + "license": "MIT" + }, + "node_modules/@alpinejs/mask": { +- "version": "3.17.0", +- "resolved": "https://registry.npmjs.org/@alpinejs/mask/-/mask-3.17.0.tgz", +- "integrity": "sha512-/VL4Sc4T3V/gzuqurOhvsO3FqUKC6RzGrNV4UJUYzv3i+tip/LXTKJIPjPKdw/qzto8c2pRFJ0lpEWPyVcYFBw==", ++ "version": "3.17.1", ++ "resolved": "https://registry.npmjs.org/@alpinejs/mask/-/mask-3.17.1.tgz", ++ "integrity": "sha512-EK/6nkVdO0kyLM/xYag6oJ2jEbQevEfsdRdjUnwJnzCcLLulUpTLo0JVRBml9XBobM614pVOEMzdbXPPI0wB9w==", + "license": "MIT" + }, + "node_modules/@alpinejs/morph": { +- "version": "3.17.0", +- "resolved": "https://registry.npmjs.org/@alpinejs/morph/-/morph-3.17.0.tgz", +- "integrity": "sha512-Jucn2wQObrNFnz8m2JR6W2G6fiYpnVu9C2Y1VWfuLDfmD1mv6tHowBevISBxQ459gL/1Iyec3jSZl3hWbyN/Mw==", ++ "version": "3.17.1", ++ "resolved": "https://registry.npmjs.org/@alpinejs/morph/-/morph-3.17.1.tgz", ++ "integrity": "sha512-RVafJn9fsF1mrxbQniSgTyneV4ybEFPgBGsjwpxko1g0WPdctTewgnxxO86gy5VztpjNvpjRW1bcpq39WtMt8w==", + "license": "MIT" + }, + "node_modules/@alpinejs/persist": { +- "version": "3.17.0", +- "resolved": "https://registry.npmjs.org/@alpinejs/persist/-/persist-3.17.0.tgz", +- "integrity": "sha512-sS4raHKnSnqfQrVgMAJhc/9cRDZ6ZiLlJqhNhboaiU986JQSOOtfKSM2n23EVmMtm/RcqDR6HqVjDjgyQyuvxg==", ++ "version": "3.17.1", ++ "resolved": "https://registry.npmjs.org/@alpinejs/persist/-/persist-3.17.1.tgz", ++ "integrity": "sha512-PN/93FIWakZYY4zB/VGDlFtx2LOoa318huflgLMo2jsk+pkjLlDkX1qmuUFh5xhI7Uj3vSvU1Eu1WIA3TN3PTA==", + "license": "MIT" + }, + "node_modules/@alpinejs/resize": { +- "version": "3.17.0", +- "resolved": "https://registry.npmjs.org/@alpinejs/resize/-/resize-3.17.0.tgz", +- "integrity": "sha512-5kVl5975Ob6O22RomUqqMnM+azIX51ckHS1eW+1y/xv0UiXFDa7V16jTz+pCRlDH9EHr9mE+wF1DbGIleI7xhg==", ++ "version": "3.17.1", ++ "resolved": "https://registry.npmjs.org/@alpinejs/resize/-/resize-3.17.1.tgz", ++ "integrity": "sha512-TyHYMY6DQBh9P/hOFH3KGLE7ilyfR3u3qsYtJfpsE6Fq8eKobkjudahmhHmdiGurohx8YaVbWBNilDcnAjLOTw==", + "license": "MIT" + }, + "node_modules/@alpinejs/sort": { +- "version": "3.17.0", +- "resolved": "https://registry.npmjs.org/@alpinejs/sort/-/sort-3.17.0.tgz", +- "integrity": "sha512-yruO0mcORzZEXWg8JSaOEKyw770x5Iu2ssi9sYnPacwJaU+R0e7rXn7VDrbg2DvevnpeKg7dZZtR3VUykF3tOA==", ++ "version": "3.17.1", ++ "resolved": "https://registry.npmjs.org/@alpinejs/sort/-/sort-3.17.1.tgz", ++ "integrity": "sha512-Q6qF00WI4cQAZdIxPgbsHnxZIiIv4T1kfSPyEy2QB/SLhLdISuIjzTBa3TQAe1P45BkRtNk5Y8fQuDZuKhN/6w==", + "license": "MIT", + "dependencies": { + "sortablejs": "^1.15.2" +@@ -1266,9 +1266,9 @@ + } + }, + "node_modules/alpinejs": { +- "version": "3.17.0", +- "resolved": "https://registry.npmjs.org/alpinejs/-/alpinejs-3.17.0.tgz", +- "integrity": "sha512-LDLcfqFsiQrdFCNqK7zWyfjx2QE2sjPw0bIPThLVHMIQATAp1dNRKga1xPSqC+71UYFiosIYblLszzzo9r9k6A==", ++ "version": "3.17.1", ++ "resolved": "https://registry.npmjs.org/alpinejs/-/alpinejs-3.17.1.tgz", ++ "integrity": "sha512-HDUhA9juSA/pNYZ5FAAlW4qNsdeVORFSVONEIu0hVasqCOqLitf15R9tCr5GBCV0ZxiZW2Qx6BYdMSF7iGLT/Q==", + "license": "MIT", + "dependencies": { + "@vue/reactivity": "~3.5.40" +diff --git a/package.json b/package.json +index 4cc18e55..94198299 100644 +--- a/package.json ++++ b/package.json +@@ -17,18 +17,18 @@ + "vitest": "^3.2.4" + }, + "dependencies": { +- "@alpinejs/anchor": "^3.17.0", +- "@alpinejs/collapse": "^3.17.0", +- "@alpinejs/csp": "^3.17.0", +- "@alpinejs/focus": "^3.17.0", +- "@alpinejs/intersect": "^3.17.0", +- "@alpinejs/mask": "^3.17.0", +- "@alpinejs/morph": "^3.17.0", +- "@alpinejs/persist": "^3.17.0", +- "@alpinejs/resize": "^3.17.0", +- "@alpinejs/sort": "^3.17.0", ++ "@alpinejs/anchor": "^3.17.1", ++ "@alpinejs/collapse": "^3.17.1", ++ "@alpinejs/csp": "^3.17.1", ++ "@alpinejs/focus": "^3.17.1", ++ "@alpinejs/intersect": "^3.17.1", ++ "@alpinejs/mask": "^3.17.1", ++ "@alpinejs/morph": "^3.17.1", ++ "@alpinejs/persist": "^3.17.1", ++ "@alpinejs/resize": "^3.17.1", ++ "@alpinejs/sort": "^3.17.1", + "@vue/reactivity": "^3.2.45", +- "alpinejs": "^3.17.0", ++ "alpinejs": "^3.17.1", + "nprogress": "^0.2.0" + } + } diff --git a/tasks/livewire__livewire-10638/solution/solve.sh b/tasks/livewire__livewire-10638/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/livewire__livewire-10638/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/livewire__livewire-10638/task.toml b/tasks/livewire__livewire-10638/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..09ad121bb1e09334b683516e9ffde5a7442ef675 --- /dev/null +++ b/tasks/livewire__livewire-10638/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/livewire__livewire-10638" +description = "Prepare Alpine 3.17.1 on main" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "livewire", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "livewire/livewire" +ref = "c755844923630a921f8bea185e75771fcb9b8c7c" +reference = "https://github.com/livewire/livewire/pull/10638" +source_access = "auto" +built_at = "2026-11-16T16:09:51.523409+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:e89093bbecba7ba65c421ece7923c30caeba499b4c78fbf386befa8a8a112dae" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-08-31T14:46:04Z" +diff_format = "unified" +context_files = [ + "package-lock.json", + "package.json", +] +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.369304+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:a552ed136444da68d35093cb6732796149882a7b2259c96966c4cf70dadcf62a" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/livewire__livewire-10638/tests/capture.py b/tasks/livewire__livewire-10638/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/livewire__livewire-10638/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/livewire__livewire-10638/tests/instruction.md b/tasks/livewire__livewire-10638/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..eee1f2fb6a8e5da29f0e1a00b3854b3d138eca28 --- /dev/null +++ b/tasks/livewire__livewire-10638/tests/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** Prepare Alpine 3.17.1 on main + +## Description + +Updates main to Alpine v3.17.1 from the published npm packages. + +Verified with a clean npm install, the full JavaScript suite (164 passed, 1 skipped), and a production build. The lockfile resolves Alpine and all bundled plugins to 3.17.1. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `c75584492363`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10638/tests/oracle.patch b/tasks/livewire__livewire-10638/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..64ff1cdc5e362aea25bf414e75714a82ac584462 --- /dev/null +++ b/tasks/livewire__livewire-10638/tests/oracle.patch @@ -0,0 +1,185 @@ +diff --git a/package-lock.json b/package-lock.json +index 18afc3dd..9dcd46c9 100644 +--- a/package-lock.json ++++ b/package-lock.json +@@ -7,18 +7,18 @@ + "name": "laravel-livewire", + "license": "MIT", + "dependencies": { +- "@alpinejs/anchor": "^3.17.0", +- "@alpinejs/collapse": "^3.17.0", +- "@alpinejs/csp": "^3.17.0", +- "@alpinejs/focus": "^3.17.0", +- "@alpinejs/intersect": "^3.17.0", +- "@alpinejs/mask": "^3.17.0", +- "@alpinejs/morph": "^3.17.0", +- "@alpinejs/persist": "^3.17.0", +- "@alpinejs/resize": "^3.17.0", +- "@alpinejs/sort": "^3.17.0", ++ "@alpinejs/anchor": "^3.17.1", ++ "@alpinejs/collapse": "^3.17.1", ++ "@alpinejs/csp": "^3.17.1", ++ "@alpinejs/focus": "^3.17.1", ++ "@alpinejs/intersect": "^3.17.1", ++ "@alpinejs/mask": "^3.17.1", ++ "@alpinejs/morph": "^3.17.1", ++ "@alpinejs/persist": "^3.17.1", ++ "@alpinejs/resize": "^3.17.1", ++ "@alpinejs/sort": "^3.17.1", + "@vue/reactivity": "^3.2.45", +- "alpinejs": "^3.17.0", ++ "alpinejs": "^3.17.1", + "nprogress": "^0.2.0" + }, + "devDependencies": { +@@ -29,33 +29,33 @@ + } + }, + "node_modules/@alpinejs/anchor": { +- "version": "3.17.0", +- "resolved": "https://registry.npmjs.org/@alpinejs/anchor/-/anchor-3.17.0.tgz", +- "integrity": "sha512-TCY8DnyMWIWdAECjTEzBsDnh4gfiKuZq2wjmS0eHY0F38i5s4k2iOphxt5cWAytLI9yw6FKqbCytXNmjHOZjDQ==", ++ "version": "3.17.1", ++ "resolved": "https://registry.npmjs.org/@alpinejs/anchor/-/anchor-3.17.1.tgz", ++ "integrity": "sha512-x6mVH3CAUKLMMh1jEgJ7pWi9DzKEgTq6pK391wN1MvSLndjr0RYOyfCakS1Y6SqHZbTyRtwfp3zG3ECoFYILKw==", + "license": "MIT", + "dependencies": { + "@floating-ui/dom": "^1.5.3" + } + }, + "node_modules/@alpinejs/collapse": { +- "version": "3.17.0", +- "resolved": "https://registry.npmjs.org/@alpinejs/collapse/-/collapse-3.17.0.tgz", +- "integrity": "sha512-Dwjb8cEjUYdHy0FCKCfmmq/RGOotSm116w/fQBXTrX2HPw5rrJ3ZUgUhO1JOgtgkOw+vTlBERPtjJViIrMZn0w==", ++ "version": "3.17.1", ++ "resolved": "https://registry.npmjs.org/@alpinejs/collapse/-/collapse-3.17.1.tgz", ++ "integrity": "sha512-ygf0kJ2I+1TgBUjS+V1Dx2KlT/y/AatyfavzL7b2T3qrPx7WRGI4yxvFB0h6J5OZVO08dhtDTVk/Z1GIC6ME/w==", + "license": "MIT" + }, + "node_modules/@alpinejs/csp": { +- "version": "3.17.0", +- "resolved": "https://registry.npmjs.org/@alpinejs/csp/-/csp-3.17.0.tgz", +- "integrity": "sha512-D6W+RbUfkU1SyAYM0GHNF84jEHtx77HQq5CdOBvlBwDzKqbdTqjITPRLNihZ/EcUqoLgqebFzHd/v55rpP0Jhw==", ++ "version": "3.17.1", ++ "resolved": "https://registry.npmjs.org/@alpinejs/csp/-/csp-3.17.1.tgz", ++ "integrity": "sha512-HDrY0ZxvJWSmeUYqtHVSsitaqy1es3VDCNodPpdQRX4nHhHiRoeib+rOzRFFStFRD/6x0KmQzJVJ4FCLAI/DUQ==", + "license": "MIT", + "dependencies": { + "@vue/reactivity": "~3.5.40" + } + }, + "node_modules/@alpinejs/focus": { +- "version": "3.17.0", +- "resolved": "https://registry.npmjs.org/@alpinejs/focus/-/focus-3.17.0.tgz", +- "integrity": "sha512-tqkE2Pj4WgSXXujs3eCLxiS2ZODgNcDsKvG5lCZKlDozeRO6WFeSAjV5EKi4p+BFNIwm1937O4xwuV7hQ0Q+jA==", ++ "version": "3.17.1", ++ "resolved": "https://registry.npmjs.org/@alpinejs/focus/-/focus-3.17.1.tgz", ++ "integrity": "sha512-23+9xUfPMhuqIm6xeqLQmQTBjNY/yHtJ5np05WrFZLdKXOXCLktpAE7ZAgmPoD/s7F2banEiJzTSFDO6GnWUIg==", + "license": "MIT", + "dependencies": { + "focus-trap": "^8.0.0", +@@ -63,39 +63,39 @@ + } + }, + "node_modules/@alpinejs/intersect": { +- "version": "3.17.0", +- "resolved": "https://registry.npmjs.org/@alpinejs/intersect/-/intersect-3.17.0.tgz", +- "integrity": "sha512-6vvZFWmPo/+Vu+vSWjKkE2KFw7HF4SLS8TaGZqnLXhrwOc3UOoYdjz798lQSYhNp1W1Z0+s/Boi4kAczt5BOkA==", ++ "version": "3.17.1", ++ "resolved": "https://registry.npmjs.org/@alpinejs/intersect/-/intersect-3.17.1.tgz", ++ "integrity": "sha512-60UZyk6BNGocHgEvKxBfgqPXq9Y1tuQ363/FjdlXc1eNI8Q0arelStWLhEyd0u8JJp7FTr50S/CmaYXMijTQYQ==", + "license": "MIT" + }, + "node_modules/@alpinejs/mask": { +- "version": "3.17.0", +- "resolved": "https://registry.npmjs.org/@alpinejs/mask/-/mask-3.17.0.tgz", +- "integrity": "sha512-/VL4Sc4T3V/gzuqurOhvsO3FqUKC6RzGrNV4UJUYzv3i+tip/LXTKJIPjPKdw/qzto8c2pRFJ0lpEWPyVcYFBw==", ++ "version": "3.17.1", ++ "resolved": "https://registry.npmjs.org/@alpinejs/mask/-/mask-3.17.1.tgz", ++ "integrity": "sha512-EK/6nkVdO0kyLM/xYag6oJ2jEbQevEfsdRdjUnwJnzCcLLulUpTLo0JVRBml9XBobM614pVOEMzdbXPPI0wB9w==", + "license": "MIT" + }, + "node_modules/@alpinejs/morph": { +- "version": "3.17.0", +- "resolved": "https://registry.npmjs.org/@alpinejs/morph/-/morph-3.17.0.tgz", +- "integrity": "sha512-Jucn2wQObrNFnz8m2JR6W2G6fiYpnVu9C2Y1VWfuLDfmD1mv6tHowBevISBxQ459gL/1Iyec3jSZl3hWbyN/Mw==", ++ "version": "3.17.1", ++ "resolved": "https://registry.npmjs.org/@alpinejs/morph/-/morph-3.17.1.tgz", ++ "integrity": "sha512-RVafJn9fsF1mrxbQniSgTyneV4ybEFPgBGsjwpxko1g0WPdctTewgnxxO86gy5VztpjNvpjRW1bcpq39WtMt8w==", + "license": "MIT" + }, + "node_modules/@alpinejs/persist": { +- "version": "3.17.0", +- "resolved": "https://registry.npmjs.org/@alpinejs/persist/-/persist-3.17.0.tgz", +- "integrity": "sha512-sS4raHKnSnqfQrVgMAJhc/9cRDZ6ZiLlJqhNhboaiU986JQSOOtfKSM2n23EVmMtm/RcqDR6HqVjDjgyQyuvxg==", ++ "version": "3.17.1", ++ "resolved": "https://registry.npmjs.org/@alpinejs/persist/-/persist-3.17.1.tgz", ++ "integrity": "sha512-PN/93FIWakZYY4zB/VGDlFtx2LOoa318huflgLMo2jsk+pkjLlDkX1qmuUFh5xhI7Uj3vSvU1Eu1WIA3TN3PTA==", + "license": "MIT" + }, + "node_modules/@alpinejs/resize": { +- "version": "3.17.0", +- "resolved": "https://registry.npmjs.org/@alpinejs/resize/-/resize-3.17.0.tgz", +- "integrity": "sha512-5kVl5975Ob6O22RomUqqMnM+azIX51ckHS1eW+1y/xv0UiXFDa7V16jTz+pCRlDH9EHr9mE+wF1DbGIleI7xhg==", ++ "version": "3.17.1", ++ "resolved": "https://registry.npmjs.org/@alpinejs/resize/-/resize-3.17.1.tgz", ++ "integrity": "sha512-TyHYMY6DQBh9P/hOFH3KGLE7ilyfR3u3qsYtJfpsE6Fq8eKobkjudahmhHmdiGurohx8YaVbWBNilDcnAjLOTw==", + "license": "MIT" + }, + "node_modules/@alpinejs/sort": { +- "version": "3.17.0", +- "resolved": "https://registry.npmjs.org/@alpinejs/sort/-/sort-3.17.0.tgz", +- "integrity": "sha512-yruO0mcORzZEXWg8JSaOEKyw770x5Iu2ssi9sYnPacwJaU+R0e7rXn7VDrbg2DvevnpeKg7dZZtR3VUykF3tOA==", ++ "version": "3.17.1", ++ "resolved": "https://registry.npmjs.org/@alpinejs/sort/-/sort-3.17.1.tgz", ++ "integrity": "sha512-Q6qF00WI4cQAZdIxPgbsHnxZIiIv4T1kfSPyEy2QB/SLhLdISuIjzTBa3TQAe1P45BkRtNk5Y8fQuDZuKhN/6w==", + "license": "MIT", + "dependencies": { + "sortablejs": "^1.15.2" +@@ -1266,9 +1266,9 @@ + } + }, + "node_modules/alpinejs": { +- "version": "3.17.0", +- "resolved": "https://registry.npmjs.org/alpinejs/-/alpinejs-3.17.0.tgz", +- "integrity": "sha512-LDLcfqFsiQrdFCNqK7zWyfjx2QE2sjPw0bIPThLVHMIQATAp1dNRKga1xPSqC+71UYFiosIYblLszzzo9r9k6A==", ++ "version": "3.17.1", ++ "resolved": "https://registry.npmjs.org/alpinejs/-/alpinejs-3.17.1.tgz", ++ "integrity": "sha512-HDUhA9juSA/pNYZ5FAAlW4qNsdeVORFSVONEIu0hVasqCOqLitf15R9tCr5GBCV0ZxiZW2Qx6BYdMSF7iGLT/Q==", + "license": "MIT", + "dependencies": { + "@vue/reactivity": "~3.5.40" +diff --git a/package.json b/package.json +index 4cc18e55..94198299 100644 +--- a/package.json ++++ b/package.json +@@ -17,18 +17,18 @@ + "vitest": "^3.2.4" + }, + "dependencies": { +- "@alpinejs/anchor": "^3.17.0", +- "@alpinejs/collapse": "^3.17.0", +- "@alpinejs/csp": "^3.17.0", +- "@alpinejs/focus": "^3.17.0", +- "@alpinejs/intersect": "^3.17.0", +- "@alpinejs/mask": "^3.17.0", +- "@alpinejs/morph": "^3.17.0", +- "@alpinejs/persist": "^3.17.0", +- "@alpinejs/resize": "^3.17.0", +- "@alpinejs/sort": "^3.17.0", ++ "@alpinejs/anchor": "^3.17.1", ++ "@alpinejs/collapse": "^3.17.1", ++ "@alpinejs/csp": "^3.17.1", ++ "@alpinejs/focus": "^3.17.1", ++ "@alpinejs/intersect": "^3.17.1", ++ "@alpinejs/mask": "^3.17.1", ++ "@alpinejs/morph": "^3.17.1", ++ "@alpinejs/persist": "^3.17.1", ++ "@alpinejs/resize": "^3.17.1", ++ "@alpinejs/sort": "^3.17.1", + "@vue/reactivity": "^3.2.45", +- "alpinejs": "^3.17.0", ++ "alpinejs": "^3.17.1", + "nprogress": "^0.2.0" + } + } diff --git a/tasks/livewire__livewire-10638/tests/test.sh b/tasks/livewire__livewire-10638/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..dd7f9c469f6220854e0efc795f075cc98ba8362f --- /dev/null +++ b/tasks/livewire__livewire-10638/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace c755844923630a921f8bea185e75771fcb9b8c7c > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/livewire__livewire-10638/tests/verifier.py b/tasks/livewire__livewire-10638/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/livewire__livewire-10638/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/livewire__livewire-10640/environment/Dockerfile b/tasks/livewire__livewire-10640/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..391fc71bcfed7a0d3a53520d976af34f834a8736 --- /dev/null +++ b/tasks/livewire__livewire-10640/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/livewire/livewire.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/livewire/livewire.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/livewire/livewire.git +WORKDIR /workspace +RUN git fetch --depth 1 origin a4c57fc1e2615745176568823a888e1a2f2d9e09 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard a4c57fc1e2615745176568823a888e1a2f2d9e09 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base a4c57fc1e2615745176568823a888e1a2f2d9e09 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/livewire__livewire-10640/instruction.md b/tasks/livewire__livewire-10640/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5368c82d5ba37317a2e507ec11f6549997e082c1 --- /dev/null +++ b/tasks/livewire__livewire-10640/instruction.md @@ -0,0 +1,31 @@ +# Issue + +**Title:** [4.x] Keep wire:dirty subscribed to every target + +## Description + +Ports #10616 from 3.x to 4.x for release synchronization. + +The 4.x helper now evaluates every target on every reactive pass so Alpine remains subscribed after an earlier target becomes clean. The original multi-target browser regression was adapted to the 4.x helper architecture. + +Verification: +- Production asset build +- Vitest: 110 passed, 1 skipped +- Focused browser regression: 1 test, 5 assertions + + + +## Summary by CodeRabbit + +* **Bug Fixes** + * Improved dirty-state tracking when multiple targets are monitored. + * Dirty indicators now update correctly after a commit when changes occur in any tracked target. + +* **Tests** + * Added coverage verifying dirty-state behavior across multiple targets and successive changes. + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `a4c57fc1e261`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10640/solution/patch.diff b/tasks/livewire__livewire-10640/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..7761ea787d186872bbb54e642c4e22711c828f0e --- /dev/null +++ b/tasks/livewire__livewire-10640/solution/patch.diff @@ -0,0 +1,68 @@ +diff --git a/js/directives/wire-dirty.js b/js/directives/wire-dirty.js +index b8d61815..3734f25e 100644 +--- a/js/directives/wire-dirty.js ++++ b/js/directives/wire-dirty.js +@@ -48,11 +48,14 @@ export function checkDirty(component, targets) { + isDirty = JSON.stringify(component.canonical) !== JSON.stringify(component.reactive) + } else if (Array.isArray(targets)) { + for (let i = 0; i < targets.length; i++) { +- if (isDirty) break; +- + let target = targets[i] + +- isDirty = JSON.stringify(dataGet(component.canonical, target)) !== JSON.stringify(dataGet(component.reactive, target)) ++ let canonical = JSON.stringify(dataGet(component.canonical, target)) ++ let reactive = JSON.stringify(dataGet(component.reactive, target)) ++ ++ if (canonical !== reactive) { ++ isDirty = true ++ } + } + } else { + isDirty = JSON.stringify(dataGet(component.canonical, targets)) !== JSON.stringify(dataGet(component.reactive, targets)) +diff --git a/src/Features/SupportDataBinding/BrowserTest.php b/src/Features/SupportDataBinding/BrowserTest.php +index f6d7c3ac..bce71ff9 100644 +--- a/src/Features/SupportDataBinding/BrowserTest.php ++++ b/src/Features/SupportDataBinding/BrowserTest.php +@@ -152,7 +152,40 @@ class BrowserTest extends BrowserTestCase + ->pause(50) + ->assertVisible('@dirty-indicator') + ; +-} ++ } ++ ++ function test_wire_dirty_keeps_tracking_every_target_after_a_commit() ++ { ++ Livewire::visit(new class extends Component { ++ public $first = false; ++ ++ public $second = ''; ++ ++ public function render() ++ { ++ return <<<'BLADE' ++
++ ++ ++ ++ ++ ++
++
++ BLADE; ++ } ++ }) ++ ->assertAttributeDoesntContain('@dirty', 'class', 'dirty') ++ ->check('@first') ++ ->pause(50) ++ ->assertAttributeContains('@dirty', 'class', 'dirty') ++ ->waitForLivewire()->click('@commit') ++ ->waitUntil("!document.querySelector('[dusk=\"dirty\"]').classList.contains('dirty')") ++ ->type('@second', 'Later target') ++ ->pause(50) ++ ->assertAttributeContains('@dirty', 'class', 'dirty') ++ ; ++ } + + function test_can_update_bound_value_from_lifecyle_hook() + { diff --git a/tasks/livewire__livewire-10640/solution/solve.sh b/tasks/livewire__livewire-10640/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/livewire__livewire-10640/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/livewire__livewire-10640/task.toml b/tasks/livewire__livewire-10640/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..c3ba4eb918d22cbdeca21cc7a035e201dddaab41 --- /dev/null +++ b/tasks/livewire__livewire-10640/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/livewire__livewire-10640" +description = "[4.x] Keep wire:dirty subscribed to every target" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "livewire", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "livewire/livewire" +ref = "a4c57fc1e2615745176568823a888e1a2f2d9e09" +reference = "https://github.com/livewire/livewire/pull/10640" +source_access = "auto" +built_at = "2026-11-16T16:09:51.526749+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:5e76bcbd49e734daa8e07559b551c23663b7467c47a08d2978773099aa282824" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-08-31T14:14:00Z" +diff_format = "unified" +context_files = [ + "js/directives/wire-dirty.js", + "src/Features/SupportDataBinding/BrowserTest.php", +] +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.369747+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:0f13c76f3d39a5d869c4b9192fc4f13e7ad867066f7174791f5a81b4e4e5f54a" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/livewire__livewire-10640/tests/capture.py b/tasks/livewire__livewire-10640/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/livewire__livewire-10640/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/livewire__livewire-10640/tests/instruction.md b/tasks/livewire__livewire-10640/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5368c82d5ba37317a2e507ec11f6549997e082c1 --- /dev/null +++ b/tasks/livewire__livewire-10640/tests/instruction.md @@ -0,0 +1,31 @@ +# Issue + +**Title:** [4.x] Keep wire:dirty subscribed to every target + +## Description + +Ports #10616 from 3.x to 4.x for release synchronization. + +The 4.x helper now evaluates every target on every reactive pass so Alpine remains subscribed after an earlier target becomes clean. The original multi-target browser regression was adapted to the 4.x helper architecture. + +Verification: +- Production asset build +- Vitest: 110 passed, 1 skipped +- Focused browser regression: 1 test, 5 assertions + + + +## Summary by CodeRabbit + +* **Bug Fixes** + * Improved dirty-state tracking when multiple targets are monitored. + * Dirty indicators now update correctly after a commit when changes occur in any tracked target. + +* **Tests** + * Added coverage verifying dirty-state behavior across multiple targets and successive changes. + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `a4c57fc1e261`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10640/tests/oracle.patch b/tasks/livewire__livewire-10640/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..7761ea787d186872bbb54e642c4e22711c828f0e --- /dev/null +++ b/tasks/livewire__livewire-10640/tests/oracle.patch @@ -0,0 +1,68 @@ +diff --git a/js/directives/wire-dirty.js b/js/directives/wire-dirty.js +index b8d61815..3734f25e 100644 +--- a/js/directives/wire-dirty.js ++++ b/js/directives/wire-dirty.js +@@ -48,11 +48,14 @@ export function checkDirty(component, targets) { + isDirty = JSON.stringify(component.canonical) !== JSON.stringify(component.reactive) + } else if (Array.isArray(targets)) { + for (let i = 0; i < targets.length; i++) { +- if (isDirty) break; +- + let target = targets[i] + +- isDirty = JSON.stringify(dataGet(component.canonical, target)) !== JSON.stringify(dataGet(component.reactive, target)) ++ let canonical = JSON.stringify(dataGet(component.canonical, target)) ++ let reactive = JSON.stringify(dataGet(component.reactive, target)) ++ ++ if (canonical !== reactive) { ++ isDirty = true ++ } + } + } else { + isDirty = JSON.stringify(dataGet(component.canonical, targets)) !== JSON.stringify(dataGet(component.reactive, targets)) +diff --git a/src/Features/SupportDataBinding/BrowserTest.php b/src/Features/SupportDataBinding/BrowserTest.php +index f6d7c3ac..bce71ff9 100644 +--- a/src/Features/SupportDataBinding/BrowserTest.php ++++ b/src/Features/SupportDataBinding/BrowserTest.php +@@ -152,7 +152,40 @@ class BrowserTest extends BrowserTestCase + ->pause(50) + ->assertVisible('@dirty-indicator') + ; +-} ++ } ++ ++ function test_wire_dirty_keeps_tracking_every_target_after_a_commit() ++ { ++ Livewire::visit(new class extends Component { ++ public $first = false; ++ ++ public $second = ''; ++ ++ public function render() ++ { ++ return <<<'BLADE' ++
++ ++ ++ ++ ++ ++
++
++ BLADE; ++ } ++ }) ++ ->assertAttributeDoesntContain('@dirty', 'class', 'dirty') ++ ->check('@first') ++ ->pause(50) ++ ->assertAttributeContains('@dirty', 'class', 'dirty') ++ ->waitForLivewire()->click('@commit') ++ ->waitUntil("!document.querySelector('[dusk=\"dirty\"]').classList.contains('dirty')") ++ ->type('@second', 'Later target') ++ ->pause(50) ++ ->assertAttributeContains('@dirty', 'class', 'dirty') ++ ; ++ } + + function test_can_update_bound_value_from_lifecyle_hook() + { diff --git a/tasks/livewire__livewire-10640/tests/test.sh b/tasks/livewire__livewire-10640/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..a3edb3ffa138c4a7d0ec2ee97b82c6257c2fb8d5 --- /dev/null +++ b/tasks/livewire__livewire-10640/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace a4c57fc1e2615745176568823a888e1a2f2d9e09 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/livewire__livewire-10640/tests/verifier.py b/tasks/livewire__livewire-10640/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/livewire__livewire-10640/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/livewire__livewire-10641/environment/Dockerfile b/tasks/livewire__livewire-10641/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..391fc71bcfed7a0d3a53520d976af34f834a8736 --- /dev/null +++ b/tasks/livewire__livewire-10641/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/livewire/livewire.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/livewire/livewire.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/livewire/livewire.git +WORKDIR /workspace +RUN git fetch --depth 1 origin a4c57fc1e2615745176568823a888e1a2f2d9e09 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard a4c57fc1e2615745176568823a888e1a2f2d9e09 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base a4c57fc1e2615745176568823a888e1a2f2d9e09 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/livewire__livewire-10641/instruction.md b/tasks/livewire__livewire-10641/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..40cf0c0c99d64a41758f6d112199841cc11723bb --- /dev/null +++ b/tasks/livewire__livewire-10641/instruction.md @@ -0,0 +1,23 @@ +# Issue + +**Title:** Prepare Alpine 3.17.1 on 4.x + +## Description + +Updates 4.x to Alpine v3.17.1 from the published npm packages. + +Verified with a clean npm install, the full JavaScript suite (110 passed, 1 skipped), and a production build. The lockfile resolves Alpine and all bundled plugins to 3.17.1. + + + +## Summary by CodeRabbit + +* **Chores** + * Updated Alpine.js and its plugins to version 3.17.1. + * Retained existing versions of Vue reactivity and progress indicator dependencies. + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `a4c57fc1e261`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10641/solution/patch.diff b/tasks/livewire__livewire-10641/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..64ff1cdc5e362aea25bf414e75714a82ac584462 --- /dev/null +++ b/tasks/livewire__livewire-10641/solution/patch.diff @@ -0,0 +1,185 @@ +diff --git a/package-lock.json b/package-lock.json +index 18afc3dd..9dcd46c9 100644 +--- a/package-lock.json ++++ b/package-lock.json +@@ -7,18 +7,18 @@ + "name": "laravel-livewire", + "license": "MIT", + "dependencies": { +- "@alpinejs/anchor": "^3.17.0", +- "@alpinejs/collapse": "^3.17.0", +- "@alpinejs/csp": "^3.17.0", +- "@alpinejs/focus": "^3.17.0", +- "@alpinejs/intersect": "^3.17.0", +- "@alpinejs/mask": "^3.17.0", +- "@alpinejs/morph": "^3.17.0", +- "@alpinejs/persist": "^3.17.0", +- "@alpinejs/resize": "^3.17.0", +- "@alpinejs/sort": "^3.17.0", ++ "@alpinejs/anchor": "^3.17.1", ++ "@alpinejs/collapse": "^3.17.1", ++ "@alpinejs/csp": "^3.17.1", ++ "@alpinejs/focus": "^3.17.1", ++ "@alpinejs/intersect": "^3.17.1", ++ "@alpinejs/mask": "^3.17.1", ++ "@alpinejs/morph": "^3.17.1", ++ "@alpinejs/persist": "^3.17.1", ++ "@alpinejs/resize": "^3.17.1", ++ "@alpinejs/sort": "^3.17.1", + "@vue/reactivity": "^3.2.45", +- "alpinejs": "^3.17.0", ++ "alpinejs": "^3.17.1", + "nprogress": "^0.2.0" + }, + "devDependencies": { +@@ -29,33 +29,33 @@ + } + }, + "node_modules/@alpinejs/anchor": { +- "version": "3.17.0", +- "resolved": "https://registry.npmjs.org/@alpinejs/anchor/-/anchor-3.17.0.tgz", +- "integrity": "sha512-TCY8DnyMWIWdAECjTEzBsDnh4gfiKuZq2wjmS0eHY0F38i5s4k2iOphxt5cWAytLI9yw6FKqbCytXNmjHOZjDQ==", ++ "version": "3.17.1", ++ "resolved": "https://registry.npmjs.org/@alpinejs/anchor/-/anchor-3.17.1.tgz", ++ "integrity": "sha512-x6mVH3CAUKLMMh1jEgJ7pWi9DzKEgTq6pK391wN1MvSLndjr0RYOyfCakS1Y6SqHZbTyRtwfp3zG3ECoFYILKw==", + "license": "MIT", + "dependencies": { + "@floating-ui/dom": "^1.5.3" + } + }, + "node_modules/@alpinejs/collapse": { +- "version": "3.17.0", +- "resolved": "https://registry.npmjs.org/@alpinejs/collapse/-/collapse-3.17.0.tgz", +- "integrity": "sha512-Dwjb8cEjUYdHy0FCKCfmmq/RGOotSm116w/fQBXTrX2HPw5rrJ3ZUgUhO1JOgtgkOw+vTlBERPtjJViIrMZn0w==", ++ "version": "3.17.1", ++ "resolved": "https://registry.npmjs.org/@alpinejs/collapse/-/collapse-3.17.1.tgz", ++ "integrity": "sha512-ygf0kJ2I+1TgBUjS+V1Dx2KlT/y/AatyfavzL7b2T3qrPx7WRGI4yxvFB0h6J5OZVO08dhtDTVk/Z1GIC6ME/w==", + "license": "MIT" + }, + "node_modules/@alpinejs/csp": { +- "version": "3.17.0", +- "resolved": "https://registry.npmjs.org/@alpinejs/csp/-/csp-3.17.0.tgz", +- "integrity": "sha512-D6W+RbUfkU1SyAYM0GHNF84jEHtx77HQq5CdOBvlBwDzKqbdTqjITPRLNihZ/EcUqoLgqebFzHd/v55rpP0Jhw==", ++ "version": "3.17.1", ++ "resolved": "https://registry.npmjs.org/@alpinejs/csp/-/csp-3.17.1.tgz", ++ "integrity": "sha512-HDrY0ZxvJWSmeUYqtHVSsitaqy1es3VDCNodPpdQRX4nHhHiRoeib+rOzRFFStFRD/6x0KmQzJVJ4FCLAI/DUQ==", + "license": "MIT", + "dependencies": { + "@vue/reactivity": "~3.5.40" + } + }, + "node_modules/@alpinejs/focus": { +- "version": "3.17.0", +- "resolved": "https://registry.npmjs.org/@alpinejs/focus/-/focus-3.17.0.tgz", +- "integrity": "sha512-tqkE2Pj4WgSXXujs3eCLxiS2ZODgNcDsKvG5lCZKlDozeRO6WFeSAjV5EKi4p+BFNIwm1937O4xwuV7hQ0Q+jA==", ++ "version": "3.17.1", ++ "resolved": "https://registry.npmjs.org/@alpinejs/focus/-/focus-3.17.1.tgz", ++ "integrity": "sha512-23+9xUfPMhuqIm6xeqLQmQTBjNY/yHtJ5np05WrFZLdKXOXCLktpAE7ZAgmPoD/s7F2banEiJzTSFDO6GnWUIg==", + "license": "MIT", + "dependencies": { + "focus-trap": "^8.0.0", +@@ -63,39 +63,39 @@ + } + }, + "node_modules/@alpinejs/intersect": { +- "version": "3.17.0", +- "resolved": "https://registry.npmjs.org/@alpinejs/intersect/-/intersect-3.17.0.tgz", +- "integrity": "sha512-6vvZFWmPo/+Vu+vSWjKkE2KFw7HF4SLS8TaGZqnLXhrwOc3UOoYdjz798lQSYhNp1W1Z0+s/Boi4kAczt5BOkA==", ++ "version": "3.17.1", ++ "resolved": "https://registry.npmjs.org/@alpinejs/intersect/-/intersect-3.17.1.tgz", ++ "integrity": "sha512-60UZyk6BNGocHgEvKxBfgqPXq9Y1tuQ363/FjdlXc1eNI8Q0arelStWLhEyd0u8JJp7FTr50S/CmaYXMijTQYQ==", + "license": "MIT" + }, + "node_modules/@alpinejs/mask": { +- "version": "3.17.0", +- "resolved": "https://registry.npmjs.org/@alpinejs/mask/-/mask-3.17.0.tgz", +- "integrity": "sha512-/VL4Sc4T3V/gzuqurOhvsO3FqUKC6RzGrNV4UJUYzv3i+tip/LXTKJIPjPKdw/qzto8c2pRFJ0lpEWPyVcYFBw==", ++ "version": "3.17.1", ++ "resolved": "https://registry.npmjs.org/@alpinejs/mask/-/mask-3.17.1.tgz", ++ "integrity": "sha512-EK/6nkVdO0kyLM/xYag6oJ2jEbQevEfsdRdjUnwJnzCcLLulUpTLo0JVRBml9XBobM614pVOEMzdbXPPI0wB9w==", + "license": "MIT" + }, + "node_modules/@alpinejs/morph": { +- "version": "3.17.0", +- "resolved": "https://registry.npmjs.org/@alpinejs/morph/-/morph-3.17.0.tgz", +- "integrity": "sha512-Jucn2wQObrNFnz8m2JR6W2G6fiYpnVu9C2Y1VWfuLDfmD1mv6tHowBevISBxQ459gL/1Iyec3jSZl3hWbyN/Mw==", ++ "version": "3.17.1", ++ "resolved": "https://registry.npmjs.org/@alpinejs/morph/-/morph-3.17.1.tgz", ++ "integrity": "sha512-RVafJn9fsF1mrxbQniSgTyneV4ybEFPgBGsjwpxko1g0WPdctTewgnxxO86gy5VztpjNvpjRW1bcpq39WtMt8w==", + "license": "MIT" + }, + "node_modules/@alpinejs/persist": { +- "version": "3.17.0", +- "resolved": "https://registry.npmjs.org/@alpinejs/persist/-/persist-3.17.0.tgz", +- "integrity": "sha512-sS4raHKnSnqfQrVgMAJhc/9cRDZ6ZiLlJqhNhboaiU986JQSOOtfKSM2n23EVmMtm/RcqDR6HqVjDjgyQyuvxg==", ++ "version": "3.17.1", ++ "resolved": "https://registry.npmjs.org/@alpinejs/persist/-/persist-3.17.1.tgz", ++ "integrity": "sha512-PN/93FIWakZYY4zB/VGDlFtx2LOoa318huflgLMo2jsk+pkjLlDkX1qmuUFh5xhI7Uj3vSvU1Eu1WIA3TN3PTA==", + "license": "MIT" + }, + "node_modules/@alpinejs/resize": { +- "version": "3.17.0", +- "resolved": "https://registry.npmjs.org/@alpinejs/resize/-/resize-3.17.0.tgz", +- "integrity": "sha512-5kVl5975Ob6O22RomUqqMnM+azIX51ckHS1eW+1y/xv0UiXFDa7V16jTz+pCRlDH9EHr9mE+wF1DbGIleI7xhg==", ++ "version": "3.17.1", ++ "resolved": "https://registry.npmjs.org/@alpinejs/resize/-/resize-3.17.1.tgz", ++ "integrity": "sha512-TyHYMY6DQBh9P/hOFH3KGLE7ilyfR3u3qsYtJfpsE6Fq8eKobkjudahmhHmdiGurohx8YaVbWBNilDcnAjLOTw==", + "license": "MIT" + }, + "node_modules/@alpinejs/sort": { +- "version": "3.17.0", +- "resolved": "https://registry.npmjs.org/@alpinejs/sort/-/sort-3.17.0.tgz", +- "integrity": "sha512-yruO0mcORzZEXWg8JSaOEKyw770x5Iu2ssi9sYnPacwJaU+R0e7rXn7VDrbg2DvevnpeKg7dZZtR3VUykF3tOA==", ++ "version": "3.17.1", ++ "resolved": "https://registry.npmjs.org/@alpinejs/sort/-/sort-3.17.1.tgz", ++ "integrity": "sha512-Q6qF00WI4cQAZdIxPgbsHnxZIiIv4T1kfSPyEy2QB/SLhLdISuIjzTBa3TQAe1P45BkRtNk5Y8fQuDZuKhN/6w==", + "license": "MIT", + "dependencies": { + "sortablejs": "^1.15.2" +@@ -1266,9 +1266,9 @@ + } + }, + "node_modules/alpinejs": { +- "version": "3.17.0", +- "resolved": "https://registry.npmjs.org/alpinejs/-/alpinejs-3.17.0.tgz", +- "integrity": "sha512-LDLcfqFsiQrdFCNqK7zWyfjx2QE2sjPw0bIPThLVHMIQATAp1dNRKga1xPSqC+71UYFiosIYblLszzzo9r9k6A==", ++ "version": "3.17.1", ++ "resolved": "https://registry.npmjs.org/alpinejs/-/alpinejs-3.17.1.tgz", ++ "integrity": "sha512-HDUhA9juSA/pNYZ5FAAlW4qNsdeVORFSVONEIu0hVasqCOqLitf15R9tCr5GBCV0ZxiZW2Qx6BYdMSF7iGLT/Q==", + "license": "MIT", + "dependencies": { + "@vue/reactivity": "~3.5.40" +diff --git a/package.json b/package.json +index 4cc18e55..94198299 100644 +--- a/package.json ++++ b/package.json +@@ -17,18 +17,18 @@ + "vitest": "^3.2.4" + }, + "dependencies": { +- "@alpinejs/anchor": "^3.17.0", +- "@alpinejs/collapse": "^3.17.0", +- "@alpinejs/csp": "^3.17.0", +- "@alpinejs/focus": "^3.17.0", +- "@alpinejs/intersect": "^3.17.0", +- "@alpinejs/mask": "^3.17.0", +- "@alpinejs/morph": "^3.17.0", +- "@alpinejs/persist": "^3.17.0", +- "@alpinejs/resize": "^3.17.0", +- "@alpinejs/sort": "^3.17.0", ++ "@alpinejs/anchor": "^3.17.1", ++ "@alpinejs/collapse": "^3.17.1", ++ "@alpinejs/csp": "^3.17.1", ++ "@alpinejs/focus": "^3.17.1", ++ "@alpinejs/intersect": "^3.17.1", ++ "@alpinejs/mask": "^3.17.1", ++ "@alpinejs/morph": "^3.17.1", ++ "@alpinejs/persist": "^3.17.1", ++ "@alpinejs/resize": "^3.17.1", ++ "@alpinejs/sort": "^3.17.1", + "@vue/reactivity": "^3.2.45", +- "alpinejs": "^3.17.0", ++ "alpinejs": "^3.17.1", + "nprogress": "^0.2.0" + } + } diff --git a/tasks/livewire__livewire-10641/solution/solve.sh b/tasks/livewire__livewire-10641/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/livewire__livewire-10641/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/livewire__livewire-10641/task.toml b/tasks/livewire__livewire-10641/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..651761f885872653a263c9329a0248622019c718 --- /dev/null +++ b/tasks/livewire__livewire-10641/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/livewire__livewire-10641" +description = "Prepare Alpine 3.17.1 on 4.x" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "livewire", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "livewire/livewire" +ref = "a4c57fc1e2615745176568823a888e1a2f2d9e09" +reference = "https://github.com/livewire/livewire/pull/10641" +source_access = "auto" +built_at = "2026-11-16T16:09:51.525100+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:747837f54bb5022f41e885435dddaa6e146b164978b1a86592f654736e343318" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-08-31T14:14:33Z" +diff_format = "unified" +context_files = [ + "package-lock.json", + "package.json", +] +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.388207+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:0f13c76f3d39a5d869c4b9192fc4f13e7ad867066f7174791f5a81b4e4e5f54a" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/livewire__livewire-10641/tests/capture.py b/tasks/livewire__livewire-10641/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/livewire__livewire-10641/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/livewire__livewire-10641/tests/instruction.md b/tasks/livewire__livewire-10641/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..40cf0c0c99d64a41758f6d112199841cc11723bb --- /dev/null +++ b/tasks/livewire__livewire-10641/tests/instruction.md @@ -0,0 +1,23 @@ +# Issue + +**Title:** Prepare Alpine 3.17.1 on 4.x + +## Description + +Updates 4.x to Alpine v3.17.1 from the published npm packages. + +Verified with a clean npm install, the full JavaScript suite (110 passed, 1 skipped), and a production build. The lockfile resolves Alpine and all bundled plugins to 3.17.1. + + + +## Summary by CodeRabbit + +* **Chores** + * Updated Alpine.js and its plugins to version 3.17.1. + * Retained existing versions of Vue reactivity and progress indicator dependencies. + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `a4c57fc1e261`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10641/tests/oracle.patch b/tasks/livewire__livewire-10641/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..64ff1cdc5e362aea25bf414e75714a82ac584462 --- /dev/null +++ b/tasks/livewire__livewire-10641/tests/oracle.patch @@ -0,0 +1,185 @@ +diff --git a/package-lock.json b/package-lock.json +index 18afc3dd..9dcd46c9 100644 +--- a/package-lock.json ++++ b/package-lock.json +@@ -7,18 +7,18 @@ + "name": "laravel-livewire", + "license": "MIT", + "dependencies": { +- "@alpinejs/anchor": "^3.17.0", +- "@alpinejs/collapse": "^3.17.0", +- "@alpinejs/csp": "^3.17.0", +- "@alpinejs/focus": "^3.17.0", +- "@alpinejs/intersect": "^3.17.0", +- "@alpinejs/mask": "^3.17.0", +- "@alpinejs/morph": "^3.17.0", +- "@alpinejs/persist": "^3.17.0", +- "@alpinejs/resize": "^3.17.0", +- "@alpinejs/sort": "^3.17.0", ++ "@alpinejs/anchor": "^3.17.1", ++ "@alpinejs/collapse": "^3.17.1", ++ "@alpinejs/csp": "^3.17.1", ++ "@alpinejs/focus": "^3.17.1", ++ "@alpinejs/intersect": "^3.17.1", ++ "@alpinejs/mask": "^3.17.1", ++ "@alpinejs/morph": "^3.17.1", ++ "@alpinejs/persist": "^3.17.1", ++ "@alpinejs/resize": "^3.17.1", ++ "@alpinejs/sort": "^3.17.1", + "@vue/reactivity": "^3.2.45", +- "alpinejs": "^3.17.0", ++ "alpinejs": "^3.17.1", + "nprogress": "^0.2.0" + }, + "devDependencies": { +@@ -29,33 +29,33 @@ + } + }, + "node_modules/@alpinejs/anchor": { +- "version": "3.17.0", +- "resolved": "https://registry.npmjs.org/@alpinejs/anchor/-/anchor-3.17.0.tgz", +- "integrity": "sha512-TCY8DnyMWIWdAECjTEzBsDnh4gfiKuZq2wjmS0eHY0F38i5s4k2iOphxt5cWAytLI9yw6FKqbCytXNmjHOZjDQ==", ++ "version": "3.17.1", ++ "resolved": "https://registry.npmjs.org/@alpinejs/anchor/-/anchor-3.17.1.tgz", ++ "integrity": "sha512-x6mVH3CAUKLMMh1jEgJ7pWi9DzKEgTq6pK391wN1MvSLndjr0RYOyfCakS1Y6SqHZbTyRtwfp3zG3ECoFYILKw==", + "license": "MIT", + "dependencies": { + "@floating-ui/dom": "^1.5.3" + } + }, + "node_modules/@alpinejs/collapse": { +- "version": "3.17.0", +- "resolved": "https://registry.npmjs.org/@alpinejs/collapse/-/collapse-3.17.0.tgz", +- "integrity": "sha512-Dwjb8cEjUYdHy0FCKCfmmq/RGOotSm116w/fQBXTrX2HPw5rrJ3ZUgUhO1JOgtgkOw+vTlBERPtjJViIrMZn0w==", ++ "version": "3.17.1", ++ "resolved": "https://registry.npmjs.org/@alpinejs/collapse/-/collapse-3.17.1.tgz", ++ "integrity": "sha512-ygf0kJ2I+1TgBUjS+V1Dx2KlT/y/AatyfavzL7b2T3qrPx7WRGI4yxvFB0h6J5OZVO08dhtDTVk/Z1GIC6ME/w==", + "license": "MIT" + }, + "node_modules/@alpinejs/csp": { +- "version": "3.17.0", +- "resolved": "https://registry.npmjs.org/@alpinejs/csp/-/csp-3.17.0.tgz", +- "integrity": "sha512-D6W+RbUfkU1SyAYM0GHNF84jEHtx77HQq5CdOBvlBwDzKqbdTqjITPRLNihZ/EcUqoLgqebFzHd/v55rpP0Jhw==", ++ "version": "3.17.1", ++ "resolved": "https://registry.npmjs.org/@alpinejs/csp/-/csp-3.17.1.tgz", ++ "integrity": "sha512-HDrY0ZxvJWSmeUYqtHVSsitaqy1es3VDCNodPpdQRX4nHhHiRoeib+rOzRFFStFRD/6x0KmQzJVJ4FCLAI/DUQ==", + "license": "MIT", + "dependencies": { + "@vue/reactivity": "~3.5.40" + } + }, + "node_modules/@alpinejs/focus": { +- "version": "3.17.0", +- "resolved": "https://registry.npmjs.org/@alpinejs/focus/-/focus-3.17.0.tgz", +- "integrity": "sha512-tqkE2Pj4WgSXXujs3eCLxiS2ZODgNcDsKvG5lCZKlDozeRO6WFeSAjV5EKi4p+BFNIwm1937O4xwuV7hQ0Q+jA==", ++ "version": "3.17.1", ++ "resolved": "https://registry.npmjs.org/@alpinejs/focus/-/focus-3.17.1.tgz", ++ "integrity": "sha512-23+9xUfPMhuqIm6xeqLQmQTBjNY/yHtJ5np05WrFZLdKXOXCLktpAE7ZAgmPoD/s7F2banEiJzTSFDO6GnWUIg==", + "license": "MIT", + "dependencies": { + "focus-trap": "^8.0.0", +@@ -63,39 +63,39 @@ + } + }, + "node_modules/@alpinejs/intersect": { +- "version": "3.17.0", +- "resolved": "https://registry.npmjs.org/@alpinejs/intersect/-/intersect-3.17.0.tgz", +- "integrity": "sha512-6vvZFWmPo/+Vu+vSWjKkE2KFw7HF4SLS8TaGZqnLXhrwOc3UOoYdjz798lQSYhNp1W1Z0+s/Boi4kAczt5BOkA==", ++ "version": "3.17.1", ++ "resolved": "https://registry.npmjs.org/@alpinejs/intersect/-/intersect-3.17.1.tgz", ++ "integrity": "sha512-60UZyk6BNGocHgEvKxBfgqPXq9Y1tuQ363/FjdlXc1eNI8Q0arelStWLhEyd0u8JJp7FTr50S/CmaYXMijTQYQ==", + "license": "MIT" + }, + "node_modules/@alpinejs/mask": { +- "version": "3.17.0", +- "resolved": "https://registry.npmjs.org/@alpinejs/mask/-/mask-3.17.0.tgz", +- "integrity": "sha512-/VL4Sc4T3V/gzuqurOhvsO3FqUKC6RzGrNV4UJUYzv3i+tip/LXTKJIPjPKdw/qzto8c2pRFJ0lpEWPyVcYFBw==", ++ "version": "3.17.1", ++ "resolved": "https://registry.npmjs.org/@alpinejs/mask/-/mask-3.17.1.tgz", ++ "integrity": "sha512-EK/6nkVdO0kyLM/xYag6oJ2jEbQevEfsdRdjUnwJnzCcLLulUpTLo0JVRBml9XBobM614pVOEMzdbXPPI0wB9w==", + "license": "MIT" + }, + "node_modules/@alpinejs/morph": { +- "version": "3.17.0", +- "resolved": "https://registry.npmjs.org/@alpinejs/morph/-/morph-3.17.0.tgz", +- "integrity": "sha512-Jucn2wQObrNFnz8m2JR6W2G6fiYpnVu9C2Y1VWfuLDfmD1mv6tHowBevISBxQ459gL/1Iyec3jSZl3hWbyN/Mw==", ++ "version": "3.17.1", ++ "resolved": "https://registry.npmjs.org/@alpinejs/morph/-/morph-3.17.1.tgz", ++ "integrity": "sha512-RVafJn9fsF1mrxbQniSgTyneV4ybEFPgBGsjwpxko1g0WPdctTewgnxxO86gy5VztpjNvpjRW1bcpq39WtMt8w==", + "license": "MIT" + }, + "node_modules/@alpinejs/persist": { +- "version": "3.17.0", +- "resolved": "https://registry.npmjs.org/@alpinejs/persist/-/persist-3.17.0.tgz", +- "integrity": "sha512-sS4raHKnSnqfQrVgMAJhc/9cRDZ6ZiLlJqhNhboaiU986JQSOOtfKSM2n23EVmMtm/RcqDR6HqVjDjgyQyuvxg==", ++ "version": "3.17.1", ++ "resolved": "https://registry.npmjs.org/@alpinejs/persist/-/persist-3.17.1.tgz", ++ "integrity": "sha512-PN/93FIWakZYY4zB/VGDlFtx2LOoa318huflgLMo2jsk+pkjLlDkX1qmuUFh5xhI7Uj3vSvU1Eu1WIA3TN3PTA==", + "license": "MIT" + }, + "node_modules/@alpinejs/resize": { +- "version": "3.17.0", +- "resolved": "https://registry.npmjs.org/@alpinejs/resize/-/resize-3.17.0.tgz", +- "integrity": "sha512-5kVl5975Ob6O22RomUqqMnM+azIX51ckHS1eW+1y/xv0UiXFDa7V16jTz+pCRlDH9EHr9mE+wF1DbGIleI7xhg==", ++ "version": "3.17.1", ++ "resolved": "https://registry.npmjs.org/@alpinejs/resize/-/resize-3.17.1.tgz", ++ "integrity": "sha512-TyHYMY6DQBh9P/hOFH3KGLE7ilyfR3u3qsYtJfpsE6Fq8eKobkjudahmhHmdiGurohx8YaVbWBNilDcnAjLOTw==", + "license": "MIT" + }, + "node_modules/@alpinejs/sort": { +- "version": "3.17.0", +- "resolved": "https://registry.npmjs.org/@alpinejs/sort/-/sort-3.17.0.tgz", +- "integrity": "sha512-yruO0mcORzZEXWg8JSaOEKyw770x5Iu2ssi9sYnPacwJaU+R0e7rXn7VDrbg2DvevnpeKg7dZZtR3VUykF3tOA==", ++ "version": "3.17.1", ++ "resolved": "https://registry.npmjs.org/@alpinejs/sort/-/sort-3.17.1.tgz", ++ "integrity": "sha512-Q6qF00WI4cQAZdIxPgbsHnxZIiIv4T1kfSPyEy2QB/SLhLdISuIjzTBa3TQAe1P45BkRtNk5Y8fQuDZuKhN/6w==", + "license": "MIT", + "dependencies": { + "sortablejs": "^1.15.2" +@@ -1266,9 +1266,9 @@ + } + }, + "node_modules/alpinejs": { +- "version": "3.17.0", +- "resolved": "https://registry.npmjs.org/alpinejs/-/alpinejs-3.17.0.tgz", +- "integrity": "sha512-LDLcfqFsiQrdFCNqK7zWyfjx2QE2sjPw0bIPThLVHMIQATAp1dNRKga1xPSqC+71UYFiosIYblLszzzo9r9k6A==", ++ "version": "3.17.1", ++ "resolved": "https://registry.npmjs.org/alpinejs/-/alpinejs-3.17.1.tgz", ++ "integrity": "sha512-HDUhA9juSA/pNYZ5FAAlW4qNsdeVORFSVONEIu0hVasqCOqLitf15R9tCr5GBCV0ZxiZW2Qx6BYdMSF7iGLT/Q==", + "license": "MIT", + "dependencies": { + "@vue/reactivity": "~3.5.40" +diff --git a/package.json b/package.json +index 4cc18e55..94198299 100644 +--- a/package.json ++++ b/package.json +@@ -17,18 +17,18 @@ + "vitest": "^3.2.4" + }, + "dependencies": { +- "@alpinejs/anchor": "^3.17.0", +- "@alpinejs/collapse": "^3.17.0", +- "@alpinejs/csp": "^3.17.0", +- "@alpinejs/focus": "^3.17.0", +- "@alpinejs/intersect": "^3.17.0", +- "@alpinejs/mask": "^3.17.0", +- "@alpinejs/morph": "^3.17.0", +- "@alpinejs/persist": "^3.17.0", +- "@alpinejs/resize": "^3.17.0", +- "@alpinejs/sort": "^3.17.0", ++ "@alpinejs/anchor": "^3.17.1", ++ "@alpinejs/collapse": "^3.17.1", ++ "@alpinejs/csp": "^3.17.1", ++ "@alpinejs/focus": "^3.17.1", ++ "@alpinejs/intersect": "^3.17.1", ++ "@alpinejs/mask": "^3.17.1", ++ "@alpinejs/morph": "^3.17.1", ++ "@alpinejs/persist": "^3.17.1", ++ "@alpinejs/resize": "^3.17.1", ++ "@alpinejs/sort": "^3.17.1", + "@vue/reactivity": "^3.2.45", +- "alpinejs": "^3.17.0", ++ "alpinejs": "^3.17.1", + "nprogress": "^0.2.0" + } + } diff --git a/tasks/livewire__livewire-10641/tests/test.sh b/tasks/livewire__livewire-10641/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..a3edb3ffa138c4a7d0ec2ee97b82c6257c2fb8d5 --- /dev/null +++ b/tasks/livewire__livewire-10641/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace a4c57fc1e2615745176568823a888e1a2f2d9e09 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/livewire__livewire-10641/tests/verifier.py b/tasks/livewire__livewire-10641/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/livewire__livewire-10641/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/livewire__livewire-10642/environment/Dockerfile b/tasks/livewire__livewire-10642/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2b0e159ee8ce195ce98a086105e83d9d0bd84fd4 --- /dev/null +++ b/tasks/livewire__livewire-10642/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/livewire/livewire.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/livewire/livewire.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/livewire/livewire.git +WORKDIR /workspace +RUN git fetch --depth 1 origin d0b4e22841d362dd213ee9602c399594d387b6ee 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard d0b4e22841d362dd213ee9602c399594d387b6ee \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base d0b4e22841d362dd213ee9602c399594d387b6ee \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/livewire__livewire-10642/instruction.md b/tasks/livewire__livewire-10642/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3f94152d9eb3cca613be38605d909e27afad5ba9 --- /dev/null +++ b/tasks/livewire__livewire-10642/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** [4.x] Clean up render state when rendering throws + +## Description + +When a component's view throws during render, Livewire skips the cleanup that runs after `$view->render()`. The `__livewire` and `_instance` view shares stay pointed at the failed component, so anything rendered afterwards in the same process, like an error page or the next test, still sees them. The same happens for `__livewire` when an island render throws, and the component is never popped off the render stack. + +This PR moves that cleanup into `finally` blocks so it runs whether or not rendering succeeds. Successful renders behave exactly as before. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d0b4e22841d3`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10642/solution/patch.diff b/tasks/livewire__livewire-10642/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..dade1c71f4fdfd5ef6586be458cf4c16efc2e4d2 --- /dev/null +++ b/tasks/livewire__livewire-10642/solution/patch.diff @@ -0,0 +1,115 @@ +diff --git a/src/Features/SupportIslands/HandlesIslands.php b/src/Features/SupportIslands/HandlesIslands.php +index 3fb9381c..93ff2757 100644 +--- a/src/Features/SupportIslands/HandlesIslands.php ++++ b/src/Features/SupportIslands/HandlesIslands.php +@@ -224,9 +224,11 @@ trait HandlesIslands + + $finish = trigger('renderIsland', $this, $name, $view, $properties); + +- $html = $view->render(); +- +- $revertShare(); ++ try { ++ $html = $view->render(); ++ } finally { ++ $revertShare(); ++ } + + $replaceHtml = function ($newHtml) use (&$html) { + $html = $newHtml; +diff --git a/src/Mechanisms/HandleComponents/HandleComponents.php b/src/Mechanisms/HandleComponents/HandleComponents.php +index 1e274ac3..0b47f1d8 100644 +--- a/src/Mechanisms/HandleComponents/HandleComponents.php ++++ b/src/Mechanisms/HandleComponents/HandleComponents.php +@@ -330,12 +330,14 @@ class HandleComponents extends Mechanism + + $viewContext = new ViewContext; + +- $html = $view->render(function ($view) use ($viewContext) { +- // Extract leftover slots, sections, and pushes before they get flushed... +- $viewContext->extractFromEnvironment($view->getFactory()); +- }); +- +- $revertA(); $revertB(); ++ try { ++ $html = $view->render(function ($view) use ($viewContext) { ++ // Extract leftover slots, sections, and pushes before they get flushed... ++ $viewContext->extractFromEnvironment($view->getFactory()); ++ }); ++ } finally { ++ $revertA(); $revertB(); ++ } + + $html = Utils::insertAttributesIntoHtmlRoot($html, [ + 'wire:id' => $component->getId(), +@@ -381,9 +383,11 @@ class HandleComponents extends Mechanism + { + array_push(static::$renderStack, $component); + +- return tap($callback(), function () { ++ try { ++ return $callback(); ++ } finally { + array_pop(static::$renderStack); +- }); ++ } + } + + protected function updateProperties($component, $updates, $data, $context) +diff --git a/src/Mechanisms/HandleComponents/UnitTest.php b/src/Mechanisms/HandleComponents/UnitTest.php +index e82bce6f..05a75da9 100644 +--- a/src/Mechanisms/HandleComponents/UnitTest.php ++++ b/src/Mechanisms/HandleComponents/UnitTest.php +@@ -333,6 +333,52 @@ class UnitTest extends \Tests\TestCase + + $this->assertCount(1, $reported); + } ++ ++ public function test_shared_view_state_is_reverted_when_render_throws() ++ { ++ try { ++ Livewire::test(new class extends Component { ++ public function render() ++ { ++ return '
{{ $undefined }}
'; ++ } ++ }); ++ } catch (\Illuminate\View\ViewException) {} ++ ++ $this->assertNull(view()->shared('__livewire')); ++ $this->assertNull(view()->shared('_instance')); ++ } ++ ++ public function test_shared_view_state_is_reverted_when_island_render_throws() ++ { ++ $component = Livewire::test(new class extends Component { ++ public bool $fail = false; ++ ++ public function breakIsland() ++ { ++ $this->fail = true; ++ $this->skipRender(); ++ $this->renderIsland('foo'); ++ } ++ ++ public function render() ++ { ++ return <<<'HTML' ++
++ @island(name: 'foo') ++
@if ($fail) {{ $undefined }} @endif
++ @endisland ++
++ HTML; ++ } ++ }); ++ ++ try { ++ $component->call('breakIsland'); ++ } catch (\Illuminate\View\ViewException) {} ++ ++ $this->assertNull(view()->shared('__livewire')); ++ } + } + + class BasicComponent extends TestComponent diff --git a/tasks/livewire__livewire-10642/solution/solve.sh b/tasks/livewire__livewire-10642/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/livewire__livewire-10642/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/livewire__livewire-10642/task.toml b/tasks/livewire__livewire-10642/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ddacee45db2d86f90a4290664e42f971b0fcc69d --- /dev/null +++ b/tasks/livewire__livewire-10642/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/livewire__livewire-10642" +description = "[4.x] Clean up render state when rendering throws" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "livewire", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "livewire/livewire" +ref = "d0b4e22841d362dd213ee9602c399594d387b6ee" +reference = "https://github.com/livewire/livewire/pull/10642" +source_access = "auto" +built_at = "2026-11-16T16:09:51.423781+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:554d0b488e0a63fe96fbd79038da843c6e8630b2a5bb50464f6eb2c2c79e05a9" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-10-07T11:50:11Z" +diff_format = "unified" +context_files = [ + "src/Features/SupportIslands/HandlesIslands.php", + "src/Mechanisms/HandleComponents/HandleComponents.php", + "src/Mechanisms/HandleComponents/UnitTest.php", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 74 +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.390061+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:108fd5bbaa619e83c7b309cc26c21beaddb12766fe0d939f64edd86f874f671a" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/livewire__livewire-10642/tests/capture.py b/tasks/livewire__livewire-10642/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/livewire__livewire-10642/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/livewire__livewire-10642/tests/instruction.md b/tasks/livewire__livewire-10642/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3f94152d9eb3cca613be38605d909e27afad5ba9 --- /dev/null +++ b/tasks/livewire__livewire-10642/tests/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** [4.x] Clean up render state when rendering throws + +## Description + +When a component's view throws during render, Livewire skips the cleanup that runs after `$view->render()`. The `__livewire` and `_instance` view shares stay pointed at the failed component, so anything rendered afterwards in the same process, like an error page or the next test, still sees them. The same happens for `__livewire` when an island render throws, and the component is never popped off the render stack. + +This PR moves that cleanup into `finally` blocks so it runs whether or not rendering succeeds. Successful renders behave exactly as before. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d0b4e22841d3`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10642/tests/oracle.patch b/tasks/livewire__livewire-10642/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..dade1c71f4fdfd5ef6586be458cf4c16efc2e4d2 --- /dev/null +++ b/tasks/livewire__livewire-10642/tests/oracle.patch @@ -0,0 +1,115 @@ +diff --git a/src/Features/SupportIslands/HandlesIslands.php b/src/Features/SupportIslands/HandlesIslands.php +index 3fb9381c..93ff2757 100644 +--- a/src/Features/SupportIslands/HandlesIslands.php ++++ b/src/Features/SupportIslands/HandlesIslands.php +@@ -224,9 +224,11 @@ trait HandlesIslands + + $finish = trigger('renderIsland', $this, $name, $view, $properties); + +- $html = $view->render(); +- +- $revertShare(); ++ try { ++ $html = $view->render(); ++ } finally { ++ $revertShare(); ++ } + + $replaceHtml = function ($newHtml) use (&$html) { + $html = $newHtml; +diff --git a/src/Mechanisms/HandleComponents/HandleComponents.php b/src/Mechanisms/HandleComponents/HandleComponents.php +index 1e274ac3..0b47f1d8 100644 +--- a/src/Mechanisms/HandleComponents/HandleComponents.php ++++ b/src/Mechanisms/HandleComponents/HandleComponents.php +@@ -330,12 +330,14 @@ class HandleComponents extends Mechanism + + $viewContext = new ViewContext; + +- $html = $view->render(function ($view) use ($viewContext) { +- // Extract leftover slots, sections, and pushes before they get flushed... +- $viewContext->extractFromEnvironment($view->getFactory()); +- }); +- +- $revertA(); $revertB(); ++ try { ++ $html = $view->render(function ($view) use ($viewContext) { ++ // Extract leftover slots, sections, and pushes before they get flushed... ++ $viewContext->extractFromEnvironment($view->getFactory()); ++ }); ++ } finally { ++ $revertA(); $revertB(); ++ } + + $html = Utils::insertAttributesIntoHtmlRoot($html, [ + 'wire:id' => $component->getId(), +@@ -381,9 +383,11 @@ class HandleComponents extends Mechanism + { + array_push(static::$renderStack, $component); + +- return tap($callback(), function () { ++ try { ++ return $callback(); ++ } finally { + array_pop(static::$renderStack); +- }); ++ } + } + + protected function updateProperties($component, $updates, $data, $context) +diff --git a/src/Mechanisms/HandleComponents/UnitTest.php b/src/Mechanisms/HandleComponents/UnitTest.php +index e82bce6f..05a75da9 100644 +--- a/src/Mechanisms/HandleComponents/UnitTest.php ++++ b/src/Mechanisms/HandleComponents/UnitTest.php +@@ -333,6 +333,52 @@ class UnitTest extends \Tests\TestCase + + $this->assertCount(1, $reported); + } ++ ++ public function test_shared_view_state_is_reverted_when_render_throws() ++ { ++ try { ++ Livewire::test(new class extends Component { ++ public function render() ++ { ++ return '
{{ $undefined }}
'; ++ } ++ }); ++ } catch (\Illuminate\View\ViewException) {} ++ ++ $this->assertNull(view()->shared('__livewire')); ++ $this->assertNull(view()->shared('_instance')); ++ } ++ ++ public function test_shared_view_state_is_reverted_when_island_render_throws() ++ { ++ $component = Livewire::test(new class extends Component { ++ public bool $fail = false; ++ ++ public function breakIsland() ++ { ++ $this->fail = true; ++ $this->skipRender(); ++ $this->renderIsland('foo'); ++ } ++ ++ public function render() ++ { ++ return <<<'HTML' ++
++ @island(name: 'foo') ++
@if ($fail) {{ $undefined }} @endif
++ @endisland ++
++ HTML; ++ } ++ }); ++ ++ try { ++ $component->call('breakIsland'); ++ } catch (\Illuminate\View\ViewException) {} ++ ++ $this->assertNull(view()->shared('__livewire')); ++ } + } + + class BasicComponent extends TestComponent diff --git a/tasks/livewire__livewire-10642/tests/test.sh b/tasks/livewire__livewire-10642/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..f4255995d98bc2c91067af5b4e4a6a330f30ec75 --- /dev/null +++ b/tasks/livewire__livewire-10642/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace d0b4e22841d362dd213ee9602c399594d387b6ee > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/livewire__livewire-10642/tests/verifier.py b/tasks/livewire__livewire-10642/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/livewire__livewire-10642/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/livewire__livewire-10648/environment/Dockerfile b/tasks/livewire__livewire-10648/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b190c47b10e6f5be8db9e2a7dcaf5dc186ad023b --- /dev/null +++ b/tasks/livewire__livewire-10648/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/livewire/livewire.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/livewire/livewire.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/livewire/livewire.git +WORKDIR /workspace +RUN git fetch --depth 1 origin ca45880b4fa6f11a6f15681af3fdd8295e627d2c 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard ca45880b4fa6f11a6f15681af3fdd8295e627d2c \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base ca45880b4fa6f11a6f15681af3fdd8295e627d2c \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/livewire__livewire-10648/instruction.md b/tasks/livewire__livewire-10648/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0205044cdaaff1de85a9de99700ef2e44db2862b --- /dev/null +++ b/tasks/livewire__livewire-10648/instruction.md @@ -0,0 +1,26 @@ +# Issue + +**Title:** Preserve browser event origins for listener requests + +## Description + +When a bubbling browser event is handled by a Livewire listener, preserve the event target as the origin of the listener request. + +This matters when the event starts outside the listening component—for example, a global toast action. Features such as data-loading can then decorate the control the user actually activated while another component performs the work. + +## Coordinated PRs + +- livewire/flux#2791 — public API and toast markup +- livewire/flux-pro#567 — action runtime and browser coverage +- livewire/livewire#10648 — cross-component request loading origin +- livewire/flux-docs#211 — documentation and interactive example + +## Verification + +- npm run build +- composer test:browser -- --filter="test_data_loading_follows_an_event_origin_into_a_different_listener_component" +- 1 browser test passed with 4 assertions + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `ca45880b4fa6`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10648/solution/patch.diff b/tasks/livewire__livewire-10648/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..2412a9d3f17d81b3c21aabd60a35caf705a1ed3e --- /dev/null +++ b/tasks/livewire__livewire-10648/solution/patch.diff @@ -0,0 +1,78 @@ +diff --git a/js/features/supportListeners.js b/js/features/supportListeners.js +index f335ba60..9116bc16 100644 +--- a/js/features/supportListeners.js ++++ b/js/features/supportListeners.js +@@ -1,4 +1,5 @@ + import { on as hook } from '@/hooks' ++import { setNextActionOrigin } from '@/request' + + hook('effect', ({ component, effects }) => { + let listeners = [] +@@ -18,6 +19,14 @@ function registerListeners(component, listeners) { + + if (e.__livewire) e.__livewire.receivedBy.push(component) + ++ // Event listeners may live in a completely different component than ++ // the element that dispatched the event (for example, a global toast). ++ // Preserve that element as the action origin so it receives data-loading ++ // for the listener's request. ++ if (e.target instanceof Element) { ++ setNextActionOrigin({ el: e.target }) ++ } ++ + component.$wire.call('__dispatch', name, e.detail || {}) + } + +@@ -42,4 +51,3 @@ function registerListeners(component, listeners) { + }) + } + +- +diff --git a/src/Features/SupportDataLoading/BrowserTest.php b/src/Features/SupportDataLoading/BrowserTest.php +index 7f820c64..9904c88c 100644 +--- a/src/Features/SupportDataLoading/BrowserTest.php ++++ b/src/Features/SupportDataLoading/BrowserTest.php +@@ -6,6 +6,43 @@ use Livewire\Livewire; + + class BrowserTest extends \Tests\BrowserTestCase + { ++ public function test_data_loading_follows_an_event_origin_into_a_different_listener_component() ++ { ++ Livewire::visit([ ++ new class extends \Livewire\Component { ++ public function render() ++ { ++ return <<<'HTML' ++
++ ++ ++
++ HTML; ++ } ++ }, ++ 'receiver' => new class extends \Livewire\Component { ++ #[\Livewire\Attributes\On('toast-action')] ++ public function handleToastAction() ++ { ++ usleep(250 * 1000); ++ } ++ ++ public function render() ++ { ++ return '
Receiver
'; ++ } ++ }, ++ ]) ++ ->waitForLivewireToLoad() ++ ->assertAttributeMissing('@toast-action', 'data-loading') ++ ->click('@toast-action') ++ ->pause(10) ++ ->assertAttribute('@toast-action', 'data-loading', 'true') ++ ->pause(350) ++ ->assertAttributeMissing('@toast-action', 'data-loading') ++ ; ++ } ++ + public function test_data_loading_attribute_is_added_to_an_element_when_it_triggers_a_request() + { + Livewire::visit([ diff --git a/tasks/livewire__livewire-10648/solution/solve.sh b/tasks/livewire__livewire-10648/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/livewire__livewire-10648/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/livewire__livewire-10648/task.toml b/tasks/livewire__livewire-10648/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..b3b805df5a875f5e78f3889f09b5fc68dec028e3 --- /dev/null +++ b/tasks/livewire__livewire-10648/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/livewire__livewire-10648" +description = "Preserve browser event origins for listener requests" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "livewire", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "livewire/livewire" +ref = "ca45880b4fa6f11a6f15681af3fdd8295e627d2c" +reference = "https://github.com/livewire/livewire/pull/10648" +source_access = "auto" +built_at = "2026-11-16T16:09:51.511912+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:097930a84a13ab012e998e4e3a62beaa721d77f50316996608c029c46477cb0f" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-04T16:48:54Z" +diff_format = "unified" +context_files = [ + "js/features/supportListeners.js", + "src/Features/SupportDataLoading/BrowserTest.php", +] +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.391755+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:2f2390ae721f22e7f98bd9abe1ac36a2c5ceabeab50941900a30b050e923e548" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/livewire__livewire-10648/tests/capture.py b/tasks/livewire__livewire-10648/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/livewire__livewire-10648/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/livewire__livewire-10648/tests/instruction.md b/tasks/livewire__livewire-10648/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0205044cdaaff1de85a9de99700ef2e44db2862b --- /dev/null +++ b/tasks/livewire__livewire-10648/tests/instruction.md @@ -0,0 +1,26 @@ +# Issue + +**Title:** Preserve browser event origins for listener requests + +## Description + +When a bubbling browser event is handled by a Livewire listener, preserve the event target as the origin of the listener request. + +This matters when the event starts outside the listening component—for example, a global toast action. Features such as data-loading can then decorate the control the user actually activated while another component performs the work. + +## Coordinated PRs + +- livewire/flux#2791 — public API and toast markup +- livewire/flux-pro#567 — action runtime and browser coverage +- livewire/livewire#10648 — cross-component request loading origin +- livewire/flux-docs#211 — documentation and interactive example + +## Verification + +- npm run build +- composer test:browser -- --filter="test_data_loading_follows_an_event_origin_into_a_different_listener_component" +- 1 browser test passed with 4 assertions + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `ca45880b4fa6`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10648/tests/oracle.patch b/tasks/livewire__livewire-10648/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..2412a9d3f17d81b3c21aabd60a35caf705a1ed3e --- /dev/null +++ b/tasks/livewire__livewire-10648/tests/oracle.patch @@ -0,0 +1,78 @@ +diff --git a/js/features/supportListeners.js b/js/features/supportListeners.js +index f335ba60..9116bc16 100644 +--- a/js/features/supportListeners.js ++++ b/js/features/supportListeners.js +@@ -1,4 +1,5 @@ + import { on as hook } from '@/hooks' ++import { setNextActionOrigin } from '@/request' + + hook('effect', ({ component, effects }) => { + let listeners = [] +@@ -18,6 +19,14 @@ function registerListeners(component, listeners) { + + if (e.__livewire) e.__livewire.receivedBy.push(component) + ++ // Event listeners may live in a completely different component than ++ // the element that dispatched the event (for example, a global toast). ++ // Preserve that element as the action origin so it receives data-loading ++ // for the listener's request. ++ if (e.target instanceof Element) { ++ setNextActionOrigin({ el: e.target }) ++ } ++ + component.$wire.call('__dispatch', name, e.detail || {}) + } + +@@ -42,4 +51,3 @@ function registerListeners(component, listeners) { + }) + } + +- +diff --git a/src/Features/SupportDataLoading/BrowserTest.php b/src/Features/SupportDataLoading/BrowserTest.php +index 7f820c64..9904c88c 100644 +--- a/src/Features/SupportDataLoading/BrowserTest.php ++++ b/src/Features/SupportDataLoading/BrowserTest.php +@@ -6,6 +6,43 @@ use Livewire\Livewire; + + class BrowserTest extends \Tests\BrowserTestCase + { ++ public function test_data_loading_follows_an_event_origin_into_a_different_listener_component() ++ { ++ Livewire::visit([ ++ new class extends \Livewire\Component { ++ public function render() ++ { ++ return <<<'HTML' ++
++ ++ ++
++ HTML; ++ } ++ }, ++ 'receiver' => new class extends \Livewire\Component { ++ #[\Livewire\Attributes\On('toast-action')] ++ public function handleToastAction() ++ { ++ usleep(250 * 1000); ++ } ++ ++ public function render() ++ { ++ return '
Receiver
'; ++ } ++ }, ++ ]) ++ ->waitForLivewireToLoad() ++ ->assertAttributeMissing('@toast-action', 'data-loading') ++ ->click('@toast-action') ++ ->pause(10) ++ ->assertAttribute('@toast-action', 'data-loading', 'true') ++ ->pause(350) ++ ->assertAttributeMissing('@toast-action', 'data-loading') ++ ; ++ } ++ + public function test_data_loading_attribute_is_added_to_an_element_when_it_triggers_a_request() + { + Livewire::visit([ diff --git a/tasks/livewire__livewire-10648/tests/test.sh b/tasks/livewire__livewire-10648/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..258c8a6c568f5afa547527bd934751c2fdca02c9 --- /dev/null +++ b/tasks/livewire__livewire-10648/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace ca45880b4fa6f11a6f15681af3fdd8295e627d2c > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/livewire__livewire-10648/tests/verifier.py b/tasks/livewire__livewire-10648/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/livewire__livewire-10648/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/livewire__livewire-10649/environment/Dockerfile b/tasks/livewire__livewire-10649/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b190c47b10e6f5be8db9e2a7dcaf5dc186ad023b --- /dev/null +++ b/tasks/livewire__livewire-10649/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/livewire/livewire.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/livewire/livewire.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/livewire/livewire.git +WORKDIR /workspace +RUN git fetch --depth 1 origin ca45880b4fa6f11a6f15681af3fdd8295e627d2c 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard ca45880b4fa6f11a6f15681af3fdd8295e627d2c \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base ca45880b4fa6f11a6f15681af3fdd8295e627d2c \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/livewire__livewire-10649/instruction.md b/tasks/livewire__livewire-10649/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8f50d321f3875b50a822c96b4887a57a4ab4c1f6 --- /dev/null +++ b/tasks/livewire__livewire-10649/instruction.md @@ -0,0 +1,46 @@ +# Issue + +**Title:** [4.x] Fix attribute forwarding throws an exception when `ComponentAttributeBag::__toString()` called + +## Description + +When mounting a Livewire component with extra params that aren't recognized as component properties or `mount()` parameters, Livewire forwards them as HTML attributes. Since v4.4.3 started passing these into the placeholder view (#10392), any structured value — an array, an Eloquent model — flows into Laravel's `ComponentAttributeBag`, and `ComponentAttributeBag::__toString()` throws a `TypeError` (`trim(): Argument #1 ($string) must be of type string, array given`) the moment `{{ $attributes }}` renders. + +Filament v5 hits this on every lazy widget, since dashboards forward a `pageFilters` array to widgets that don't declare it (https://github.com/filamentphp/filament/discussions/14171). + +```blade + +{{-- 💥 TypeError in the placeholder before this PR --}} +``` + +## Findings + +- The crash isn't limited to placeholders: `render`, `renderIsland`, and `renderPlaceholder` all build a `ComponentAttributeBag` from the raw forwarded params, so all three paths can throw (#10647 only covered the placeholder). +- The `dehydrate` hook also reads the raw attributes and serializes them into the `wire:snapshot` memo. On current 4.x, passing an Eloquent model as an unmatched param embeds the model's **entire JSON representation (including non-`$hidden` columns) into the page HTML** — even when no view ever touches `$attributes`. An array also round-trips through the memo and crashes on a later render. + +## Potential solutions + +- **Filter at each render site** (#10647's approach) — fixes the placeholder crash only; misses `render`/`renderIsland` and, critically, the `dehydrate` snapshot leak. +- **Filter in `getHtmlAttributes()`** — one choke point covering every consumer: all three render paths *and* `dehydrate`, so structured values never reach the bag and never reach the snapshot. Any future consumer of forwarded attributes is safe by default. +- **Filter earlier, in `separateParamsAndAttributes()`** — semantically pure ("an array was never an HTML attribute"), but leaves the public `withHtmlAttributes()` API unguarded for direct callers. + +## Proposed solution + +Filter in `getHtmlAttributes()` so every read is clean: + +- Scalars (and `null`) are forwarded unchanged — normal attribute values, including booleans. +- `Htmlable` objects (e.g. `HtmlString`) are preserved — they explicitly represent renderable content. +- Arrays and all other objects are silently discarded, matching v3's behavior of ignoring unmatched extra params — which is what forwarding consumers like Filament rely on. + +Silently dropping (rather than throwing) is deliberate: Filament intentionally over-passes params to components that may or may not declare them. + +## Tests + +Unit tests cover arrays, Eloquent models, and `Htmlable` values across all three render paths (`render`, island, placeholder), plus a regression test asserting structured values are no longer dehydrated into the `wire:snapshot`. + +Fixes: +Closes: + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `ca45880b4fa6`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10649/solution/patch.diff b/tasks/livewire__livewire-10649/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..aa5e042494f80f07f3fd3a10f4b3865dfe783b5e --- /dev/null +++ b/tasks/livewire__livewire-10649/solution/patch.diff @@ -0,0 +1,251 @@ +diff --git a/docs/nesting.md b/docs/nesting.md +index 553a6e10..801cd051 100644 +--- a/docs/nesting.md ++++ b/docs/nesting.md +@@ -429,6 +429,8 @@ You can apply these attributes in the child component using the `$attributes` va + + Attributes that match public property names are automatically passed as props and excluded from `$attributes`. Any remaining attributes like `class`, `id`, or `data-*` are available through `$attributes`. + ++Only values that can be rendered as an HTML attribute are forwarded. Arrays and objects (other than `Htmlable` instances like `HtmlString`) are silently discarded rather than passed through `$attributes`. ++ + ## Islands vs nested components + + When building Livewire applications, you'll often face a choice: Should you create a nested child component or use an island? Both approaches allow you to isolate updates to specific regions, but they serve different purposes. +diff --git a/src/Features/SupportHtmlAttributeForwarding/HandlesHtmlAttributeForwarding.php b/src/Features/SupportHtmlAttributeForwarding/HandlesHtmlAttributeForwarding.php +index 15d359b5..14d95025 100644 +--- a/src/Features/SupportHtmlAttributeForwarding/HandlesHtmlAttributeForwarding.php ++++ b/src/Features/SupportHtmlAttributeForwarding/HandlesHtmlAttributeForwarding.php +@@ -2,6 +2,8 @@ + + namespace Livewire\Features\SupportHtmlAttributeForwarding; + ++use Illuminate\Contracts\Support\Htmlable; ++ + trait HandlesHtmlAttributeForwarding + { + protected array $htmlAttributes = []; +@@ -15,6 +17,11 @@ trait HandlesHtmlAttributeForwarding + + public function getHtmlAttributes(): array + { +- return $this->htmlAttributes; ++ // Structured values like arrays and objects can't be rendered as HTML ++ // attribute values, so only scalars and Htmlable objects are forwarded... ++ return array_filter( ++ $this->htmlAttributes, ++ fn ($value) => is_scalar($value) || is_null($value) || $value instanceof Htmlable ++ ); + } +-} +\ No newline at end of file ++} +diff --git a/src/Features/SupportHtmlAttributeForwarding/UnitTest.php b/src/Features/SupportHtmlAttributeForwarding/UnitTest.php +index 4ea1a914..507be6cb 100644 +--- a/src/Features/SupportHtmlAttributeForwarding/UnitTest.php ++++ b/src/Features/SupportHtmlAttributeForwarding/UnitTest.php +@@ -2,9 +2,14 @@ + + namespace Livewire\Features\SupportHtmlAttributeForwarding; + ++use Illuminate\Database\Eloquent\Model; ++use Illuminate\Support\HtmlString; + use Tests\TestCase; + use Livewire\Livewire; + use Livewire\Component; ++use Livewire\Attributes\Lazy; ++use Livewire\Features\SupportLazyLoading\SupportLazyLoading; ++use Sushi\Sushi; + + class UnitTest extends TestCase + { +@@ -47,4 +52,190 @@ class UnitTest extends TestCase + ->assertSeeHtml('data-testid="my-alert"') + ; + } ++ ++ public function test_array_is_not_forwarded_as_html_attribute_to_component_placeholder() ++ { ++ SupportLazyLoading::$disableWhileTesting = false; ++ ++ Livewire::component('alert', LazyAlert::class); ++ ++ $html = Livewire::mount('alert', [ ++ 'lazy' => true, ++ 'pageFilters' => ['status' => 'active'], ++ 'id' => 'error-alert', ++ ]); ++ ++ $this->assertStringContainsString('id="error-alert"', $html); ++ $this->assertStringNotContainsString('pageFilters=', $html); ++ } ++ ++ public function test_array_is_not_forwarded_as_html_attribute_to_component_render() ++ { ++ Livewire::component('alert', AlertWithAttributes::class); ++ ++ $html = Livewire::mount('alert', [ ++ 'pageFilters' => ['status' => 'active'], ++ 'id' => 'error-alert', ++ ]); ++ ++ $this->assertStringContainsString('id="error-alert"', $html); ++ $this->assertStringNotContainsString('pageFilters=', $html); ++ } ++ ++ public function test_array_is_not_forwarded_as_html_attribute_to_an_island() ++ { ++ Livewire::component('alert', AlertWithIslandAttributes::class); ++ ++ $html = Livewire::mount('alert', [ ++ 'pageFilters' => ['status' => 'active'], ++ 'id' => 'error-alert', ++ ]); ++ ++ $this->assertStringContainsString('id="error-alert"', $html); ++ $this->assertStringNotContainsString('pageFilters=', $html); ++ } ++ ++ public function test_eloquent_model_is_not_forwarded_as_html_attribute_to_component_placeholder() ++ { ++ SupportLazyLoading::$disableWhileTesting = false; ++ ++ Livewire::component('alert', LazyAlert::class); ++ ++ $html = Livewire::mount('alert', [ ++ 'lazy' => true, ++ 'record' => RecordModel::first(), ++ 'id' => 'error-alert', ++ ]); ++ ++ $this->assertStringContainsString('id="error-alert"', $html); ++ $this->assertStringNotContainsString('record=', $html); ++ } ++ ++ public function test_eloquent_model_is_not_forwarded_as_html_attribute_to_component_render() ++ { ++ Livewire::component('alert', AlertWithAttributes::class); ++ ++ $html = Livewire::mount('alert', [ ++ 'record' => RecordModel::first(), ++ 'id' => 'error-alert', ++ ]); ++ ++ $this->assertStringContainsString('id="error-alert"', $html); ++ $this->assertStringNotContainsString('record=', $html); ++ } ++ ++ public function test_eloquent_model_is_not_forwarded_as_html_attribute_to_an_island() ++ { ++ Livewire::component('alert', AlertWithIslandAttributes::class); ++ ++ $html = Livewire::mount('alert', [ ++ 'record' => RecordModel::first(), ++ 'id' => 'error-alert', ++ ]); ++ ++ $this->assertStringContainsString('id="error-alert"', $html); ++ $this->assertStringNotContainsString('record=', $html); ++ } ++ ++ public function test_htmlable_objects_are_forwarded_as_html_attributes_to_component_placeholder() ++ { ++ SupportLazyLoading::$disableWhileTesting = false; ++ ++ Livewire::component('alert', LazyAlert::class); ++ ++ $html = Livewire::mount('alert', [ ++ 'lazy' => true, ++ 'id' => 'error-alert', ++ 'title' => new HtmlString('Hello World'), ++ ]); ++ ++ $this->assertStringContainsString('id="error-alert"', $html); ++ $this->assertStringContainsString('title="Hello World"', $html); ++ } ++ ++ public function test_htmlable_objects_are_forwarded_as_html_attributes_to_component_render() ++ { ++ Livewire::component('alert', AlertWithAttributes::class); ++ ++ $html = Livewire::mount('alert', [ ++ 'id' => 'error-alert', ++ 'title' => new HtmlString('Hello World'), ++ ]); ++ ++ $this->assertStringContainsString('id="error-alert"', $html); ++ $this->assertStringContainsString('title="Hello World"', $html); ++ } ++ ++ public function test_htmlable_objects_are_forwarded_as_html_attributes_to_an_island() ++ { ++ Livewire::component('alert', AlertWithIslandAttributes::class); ++ ++ $html = Livewire::mount('alert', [ ++ 'id' => 'error-alert', ++ 'title' => new HtmlString('Hello World'), ++ ]); ++ ++ $this->assertStringContainsString('id="error-alert"', $html); ++ $this->assertStringContainsString('title="Hello World"', $html); ++ } ++ ++ public function test_arrays_and_objects_are_not_dehydrated_into_the_component_snapshot() ++ { ++ Livewire::component('alert', AlertWithAttributes::class); ++ ++ $html = Livewire::mount('alert', [ ++ 'record' => RecordModel::first(), ++ 'pageFilters' => ['status' => 'active'], ++ 'id' => 'error-alert', ++ ]); ++ ++ // Without filtering, these would be serialized into the wire:snapshot attribute... ++ $this->assertStringNotContainsString('first@example.com', $html); ++ $this->assertStringNotContainsString('pageFilters', $html); ++ } ++} ++ ++class RecordModel extends Model ++{ ++ use Sushi; ++ ++ protected $rows = [ ++ ['id' => 1, 'name' => 'First User', 'email' => 'first@example.com'], ++ ]; ++} ++ ++#[Lazy] ++class LazyAlert extends Component ++{ ++ public function placeholder() ++ { ++ return '
Loading...
'; ++ } ++ ++ public function render() ++ { ++ return '
Alert
'; ++ } ++} ++ ++class AlertWithAttributes extends Component ++{ ++ public function render() ++ { ++ return '
Alert
'; ++ } ++} ++ ++class AlertWithIslandAttributes extends Component ++{ ++ public function render() ++ { ++ return <<<'HTML' ++
++ @island(name: 'content') ++
Island
++ @endisland ++
++ HTML; ++ } + } diff --git a/tasks/livewire__livewire-10649/solution/solve.sh b/tasks/livewire__livewire-10649/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/livewire__livewire-10649/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/livewire__livewire-10649/task.toml b/tasks/livewire__livewire-10649/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..68f05371b4c200156722bfe2cbea0d36f67a9fe3 --- /dev/null +++ b/tasks/livewire__livewire-10649/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/livewire__livewire-10649" +description = "[4.x] Fix attribute forwarding throws an exception when `ComponentAttributeBag::__toString()` called" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "livewire", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "livewire/livewire" +ref = "ca45880b4fa6f11a6f15681af3fdd8295e627d2c" +reference = "https://github.com/livewire/livewire/pull/10649" +source_access = "auto" +built_at = "2026-11-16T16:09:51.521428+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:a30c1b730a23b57ff7a1035c46a7c5419578144a68502b7159d8e7af4d4bb20e" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-01T20:38:15Z" +diff_format = "unified" +context_files = [ + "docs/nesting.md", + "src/Features/SupportHtmlAttributeForwarding/HandlesHtmlAttributeForwarding.php", + "src/Features/SupportHtmlAttributeForwarding/UnitTest.php", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 204 +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.392606+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:2f2390ae721f22e7f98bd9abe1ac36a2c5ceabeab50941900a30b050e923e548" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/livewire__livewire-10649/tests/capture.py b/tasks/livewire__livewire-10649/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/livewire__livewire-10649/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/livewire__livewire-10649/tests/instruction.md b/tasks/livewire__livewire-10649/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8f50d321f3875b50a822c96b4887a57a4ab4c1f6 --- /dev/null +++ b/tasks/livewire__livewire-10649/tests/instruction.md @@ -0,0 +1,46 @@ +# Issue + +**Title:** [4.x] Fix attribute forwarding throws an exception when `ComponentAttributeBag::__toString()` called + +## Description + +When mounting a Livewire component with extra params that aren't recognized as component properties or `mount()` parameters, Livewire forwards them as HTML attributes. Since v4.4.3 started passing these into the placeholder view (#10392), any structured value — an array, an Eloquent model — flows into Laravel's `ComponentAttributeBag`, and `ComponentAttributeBag::__toString()` throws a `TypeError` (`trim(): Argument #1 ($string) must be of type string, array given`) the moment `{{ $attributes }}` renders. + +Filament v5 hits this on every lazy widget, since dashboards forward a `pageFilters` array to widgets that don't declare it (https://github.com/filamentphp/filament/discussions/14171). + +```blade + +{{-- 💥 TypeError in the placeholder before this PR --}} +``` + +## Findings + +- The crash isn't limited to placeholders: `render`, `renderIsland`, and `renderPlaceholder` all build a `ComponentAttributeBag` from the raw forwarded params, so all three paths can throw (#10647 only covered the placeholder). +- The `dehydrate` hook also reads the raw attributes and serializes them into the `wire:snapshot` memo. On current 4.x, passing an Eloquent model as an unmatched param embeds the model's **entire JSON representation (including non-`$hidden` columns) into the page HTML** — even when no view ever touches `$attributes`. An array also round-trips through the memo and crashes on a later render. + +## Potential solutions + +- **Filter at each render site** (#10647's approach) — fixes the placeholder crash only; misses `render`/`renderIsland` and, critically, the `dehydrate` snapshot leak. +- **Filter in `getHtmlAttributes()`** — one choke point covering every consumer: all three render paths *and* `dehydrate`, so structured values never reach the bag and never reach the snapshot. Any future consumer of forwarded attributes is safe by default. +- **Filter earlier, in `separateParamsAndAttributes()`** — semantically pure ("an array was never an HTML attribute"), but leaves the public `withHtmlAttributes()` API unguarded for direct callers. + +## Proposed solution + +Filter in `getHtmlAttributes()` so every read is clean: + +- Scalars (and `null`) are forwarded unchanged — normal attribute values, including booleans. +- `Htmlable` objects (e.g. `HtmlString`) are preserved — they explicitly represent renderable content. +- Arrays and all other objects are silently discarded, matching v3's behavior of ignoring unmatched extra params — which is what forwarding consumers like Filament rely on. + +Silently dropping (rather than throwing) is deliberate: Filament intentionally over-passes params to components that may or may not declare them. + +## Tests + +Unit tests cover arrays, Eloquent models, and `Htmlable` values across all three render paths (`render`, island, placeholder), plus a regression test asserting structured values are no longer dehydrated into the `wire:snapshot`. + +Fixes: +Closes: + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `ca45880b4fa6`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10649/tests/oracle.patch b/tasks/livewire__livewire-10649/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..aa5e042494f80f07f3fd3a10f4b3865dfe783b5e --- /dev/null +++ b/tasks/livewire__livewire-10649/tests/oracle.patch @@ -0,0 +1,251 @@ +diff --git a/docs/nesting.md b/docs/nesting.md +index 553a6e10..801cd051 100644 +--- a/docs/nesting.md ++++ b/docs/nesting.md +@@ -429,6 +429,8 @@ You can apply these attributes in the child component using the `$attributes` va + + Attributes that match public property names are automatically passed as props and excluded from `$attributes`. Any remaining attributes like `class`, `id`, or `data-*` are available through `$attributes`. + ++Only values that can be rendered as an HTML attribute are forwarded. Arrays and objects (other than `Htmlable` instances like `HtmlString`) are silently discarded rather than passed through `$attributes`. ++ + ## Islands vs nested components + + When building Livewire applications, you'll often face a choice: Should you create a nested child component or use an island? Both approaches allow you to isolate updates to specific regions, but they serve different purposes. +diff --git a/src/Features/SupportHtmlAttributeForwarding/HandlesHtmlAttributeForwarding.php b/src/Features/SupportHtmlAttributeForwarding/HandlesHtmlAttributeForwarding.php +index 15d359b5..14d95025 100644 +--- a/src/Features/SupportHtmlAttributeForwarding/HandlesHtmlAttributeForwarding.php ++++ b/src/Features/SupportHtmlAttributeForwarding/HandlesHtmlAttributeForwarding.php +@@ -2,6 +2,8 @@ + + namespace Livewire\Features\SupportHtmlAttributeForwarding; + ++use Illuminate\Contracts\Support\Htmlable; ++ + trait HandlesHtmlAttributeForwarding + { + protected array $htmlAttributes = []; +@@ -15,6 +17,11 @@ trait HandlesHtmlAttributeForwarding + + public function getHtmlAttributes(): array + { +- return $this->htmlAttributes; ++ // Structured values like arrays and objects can't be rendered as HTML ++ // attribute values, so only scalars and Htmlable objects are forwarded... ++ return array_filter( ++ $this->htmlAttributes, ++ fn ($value) => is_scalar($value) || is_null($value) || $value instanceof Htmlable ++ ); + } +-} +\ No newline at end of file ++} +diff --git a/src/Features/SupportHtmlAttributeForwarding/UnitTest.php b/src/Features/SupportHtmlAttributeForwarding/UnitTest.php +index 4ea1a914..507be6cb 100644 +--- a/src/Features/SupportHtmlAttributeForwarding/UnitTest.php ++++ b/src/Features/SupportHtmlAttributeForwarding/UnitTest.php +@@ -2,9 +2,14 @@ + + namespace Livewire\Features\SupportHtmlAttributeForwarding; + ++use Illuminate\Database\Eloquent\Model; ++use Illuminate\Support\HtmlString; + use Tests\TestCase; + use Livewire\Livewire; + use Livewire\Component; ++use Livewire\Attributes\Lazy; ++use Livewire\Features\SupportLazyLoading\SupportLazyLoading; ++use Sushi\Sushi; + + class UnitTest extends TestCase + { +@@ -47,4 +52,190 @@ class UnitTest extends TestCase + ->assertSeeHtml('data-testid="my-alert"') + ; + } ++ ++ public function test_array_is_not_forwarded_as_html_attribute_to_component_placeholder() ++ { ++ SupportLazyLoading::$disableWhileTesting = false; ++ ++ Livewire::component('alert', LazyAlert::class); ++ ++ $html = Livewire::mount('alert', [ ++ 'lazy' => true, ++ 'pageFilters' => ['status' => 'active'], ++ 'id' => 'error-alert', ++ ]); ++ ++ $this->assertStringContainsString('id="error-alert"', $html); ++ $this->assertStringNotContainsString('pageFilters=', $html); ++ } ++ ++ public function test_array_is_not_forwarded_as_html_attribute_to_component_render() ++ { ++ Livewire::component('alert', AlertWithAttributes::class); ++ ++ $html = Livewire::mount('alert', [ ++ 'pageFilters' => ['status' => 'active'], ++ 'id' => 'error-alert', ++ ]); ++ ++ $this->assertStringContainsString('id="error-alert"', $html); ++ $this->assertStringNotContainsString('pageFilters=', $html); ++ } ++ ++ public function test_array_is_not_forwarded_as_html_attribute_to_an_island() ++ { ++ Livewire::component('alert', AlertWithIslandAttributes::class); ++ ++ $html = Livewire::mount('alert', [ ++ 'pageFilters' => ['status' => 'active'], ++ 'id' => 'error-alert', ++ ]); ++ ++ $this->assertStringContainsString('id="error-alert"', $html); ++ $this->assertStringNotContainsString('pageFilters=', $html); ++ } ++ ++ public function test_eloquent_model_is_not_forwarded_as_html_attribute_to_component_placeholder() ++ { ++ SupportLazyLoading::$disableWhileTesting = false; ++ ++ Livewire::component('alert', LazyAlert::class); ++ ++ $html = Livewire::mount('alert', [ ++ 'lazy' => true, ++ 'record' => RecordModel::first(), ++ 'id' => 'error-alert', ++ ]); ++ ++ $this->assertStringContainsString('id="error-alert"', $html); ++ $this->assertStringNotContainsString('record=', $html); ++ } ++ ++ public function test_eloquent_model_is_not_forwarded_as_html_attribute_to_component_render() ++ { ++ Livewire::component('alert', AlertWithAttributes::class); ++ ++ $html = Livewire::mount('alert', [ ++ 'record' => RecordModel::first(), ++ 'id' => 'error-alert', ++ ]); ++ ++ $this->assertStringContainsString('id="error-alert"', $html); ++ $this->assertStringNotContainsString('record=', $html); ++ } ++ ++ public function test_eloquent_model_is_not_forwarded_as_html_attribute_to_an_island() ++ { ++ Livewire::component('alert', AlertWithIslandAttributes::class); ++ ++ $html = Livewire::mount('alert', [ ++ 'record' => RecordModel::first(), ++ 'id' => 'error-alert', ++ ]); ++ ++ $this->assertStringContainsString('id="error-alert"', $html); ++ $this->assertStringNotContainsString('record=', $html); ++ } ++ ++ public function test_htmlable_objects_are_forwarded_as_html_attributes_to_component_placeholder() ++ { ++ SupportLazyLoading::$disableWhileTesting = false; ++ ++ Livewire::component('alert', LazyAlert::class); ++ ++ $html = Livewire::mount('alert', [ ++ 'lazy' => true, ++ 'id' => 'error-alert', ++ 'title' => new HtmlString('Hello World'), ++ ]); ++ ++ $this->assertStringContainsString('id="error-alert"', $html); ++ $this->assertStringContainsString('title="Hello World"', $html); ++ } ++ ++ public function test_htmlable_objects_are_forwarded_as_html_attributes_to_component_render() ++ { ++ Livewire::component('alert', AlertWithAttributes::class); ++ ++ $html = Livewire::mount('alert', [ ++ 'id' => 'error-alert', ++ 'title' => new HtmlString('Hello World'), ++ ]); ++ ++ $this->assertStringContainsString('id="error-alert"', $html); ++ $this->assertStringContainsString('title="Hello World"', $html); ++ } ++ ++ public function test_htmlable_objects_are_forwarded_as_html_attributes_to_an_island() ++ { ++ Livewire::component('alert', AlertWithIslandAttributes::class); ++ ++ $html = Livewire::mount('alert', [ ++ 'id' => 'error-alert', ++ 'title' => new HtmlString('Hello World'), ++ ]); ++ ++ $this->assertStringContainsString('id="error-alert"', $html); ++ $this->assertStringContainsString('title="Hello World"', $html); ++ } ++ ++ public function test_arrays_and_objects_are_not_dehydrated_into_the_component_snapshot() ++ { ++ Livewire::component('alert', AlertWithAttributes::class); ++ ++ $html = Livewire::mount('alert', [ ++ 'record' => RecordModel::first(), ++ 'pageFilters' => ['status' => 'active'], ++ 'id' => 'error-alert', ++ ]); ++ ++ // Without filtering, these would be serialized into the wire:snapshot attribute... ++ $this->assertStringNotContainsString('first@example.com', $html); ++ $this->assertStringNotContainsString('pageFilters', $html); ++ } ++} ++ ++class RecordModel extends Model ++{ ++ use Sushi; ++ ++ protected $rows = [ ++ ['id' => 1, 'name' => 'First User', 'email' => 'first@example.com'], ++ ]; ++} ++ ++#[Lazy] ++class LazyAlert extends Component ++{ ++ public function placeholder() ++ { ++ return '
Loading...
'; ++ } ++ ++ public function render() ++ { ++ return '
Alert
'; ++ } ++} ++ ++class AlertWithAttributes extends Component ++{ ++ public function render() ++ { ++ return '
Alert
'; ++ } ++} ++ ++class AlertWithIslandAttributes extends Component ++{ ++ public function render() ++ { ++ return <<<'HTML' ++
++ @island(name: 'content') ++
Island
++ @endisland ++
++ HTML; ++ } + } diff --git a/tasks/livewire__livewire-10649/tests/test.sh b/tasks/livewire__livewire-10649/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..258c8a6c568f5afa547527bd934751c2fdca02c9 --- /dev/null +++ b/tasks/livewire__livewire-10649/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace ca45880b4fa6f11a6f15681af3fdd8295e627d2c > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/livewire__livewire-10649/tests/verifier.py b/tasks/livewire__livewire-10649/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/livewire__livewire-10649/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/livewire__livewire-10650/environment/Dockerfile b/tasks/livewire__livewire-10650/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b190c47b10e6f5be8db9e2a7dcaf5dc186ad023b --- /dev/null +++ b/tasks/livewire__livewire-10650/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/livewire/livewire.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/livewire/livewire.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/livewire/livewire.git +WORKDIR /workspace +RUN git fetch --depth 1 origin ca45880b4fa6f11a6f15681af3fdd8295e627d2c 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard ca45880b4fa6f11a6f15681af3fdd8295e627d2c \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base ca45880b4fa6f11a6f15681af3fdd8295e627d2c \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/livewire__livewire-10650/instruction.md b/tasks/livewire__livewire-10650/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..43f4a907b58b4c6676f4d1704584134949c1cdf5 --- /dev/null +++ b/tasks/livewire__livewire-10650/instruction.md @@ -0,0 +1,52 @@ +# Issue + +**Title:** [4.x] Fix lazy island hydration with nested reactive/modelable children + +## Description + +When a component renders multiple visible lazy islands alongside a nested child with a `#[Reactive]` (or `#[Modelable]`) property, only the first island hydrates — the rest are stuck on their loading placeholders forever. Without the nested child, all islands load fine. + +```blade +@island(name: 'one', lazy: true, always: true) + @placeholder
Loading one...
@endplaceholder +
One
+@endisland + +@island(name: 'two', lazy: true, always: true) + @placeholder
Loading two...
@endplaceholder +
Two
+@endisland + + {{-- child with a #[Reactive] prop --}} +``` + +Regression introduced by #10529. Minimized reproduction in #10644. + +## Findings + +- Each visible lazy island fires its own `__lazyLoadIsland` action, and island actions are scoped per-island — so islands `one` and `two` produce two separate pending messages *for the same component*. +- The reactive/modelable partition interceptor in `js/request/interactions.js` bundles a child `$commit` into any outgoing message whose component has bound children. Island one's message compiles into a request alongside the child `$commit`; island two's message then bundles the *same* child message, and the merge logic in `compileRequest` pulls island two into island one's request. +- That yields one request containing two messages for the same component. The response handler matches payloads to messages by component id, so each island message processes *both* payloads. Under the sequential island morph handling introduced in #10529, the second island's hydration never lands. +- The bundled child `$commit` is pure waste for island-only messages anyway: island calls skip the parent's full render on the server (`SupportIslands::call()` renders only the island, and `__lazyLoadIsland` returns early before ever touching component state), so the child stub is never re-rendered and its reactive props can't receive new values. + +## Potential solutions + +- **Skip child bundling for island-only messages** — a one-line guard reusing the existing `Message.hasActionForComponent()` helper. Fixes the whole class of stalls (concurrent lazy loads, island polls, island-scoped actions), not just lazy loading. +- Narrow the skip to `__lazyLoadIsland` calls only — but the same stall stays reachable through any two concurrent island-scoped messages (e.g. two polling islands). +- Rework the `compileRequest` merge logic so a request can never contain two messages for the same component — addresses the collision at its root but is more invasive, and island messages still shouldn't bundle children they can't update. + +## Proposed solution + +Skip reactive/modelable child bundling for island-only messages (`! message.hasActionForComponent()`). + +- Concurrent visible lazy islands hydrate independently again +- Normal component updates still bundle reactive/modelable children exactly as before (covered by the new tests' toggle/typing assertions) +- Existing island ordering behavior is untouched + +--- + +Note: with this change, actions fired from *inside* an island no longer sync reactive children in the same request. For children outside islands that sync was always a no-op render (the parent template never re-renders during an island request, so the child could never receive new prop values). A reactive child nested *inside* an island is the one case that loses live syncing — consistent with islands' scoped-render semantics, and previously untested. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `ca45880b4fa6`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10650/solution/patch.diff b/tasks/livewire__livewire-10650/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..ae68022694607901330cae4935a49ac9fb2e2bb8 --- /dev/null +++ b/tasks/livewire__livewire-10650/solution/patch.diff @@ -0,0 +1,112 @@ +diff --git a/js/request/interactions.js b/js/request/interactions.js +index 0f6ebd97..dd7068fe 100644 +--- a/js/request/interactions.js ++++ b/js/request/interactions.js +@@ -21,6 +21,12 @@ export function coordinateNetworkInteractions(messageBus) { + + // Handle modelable/reactive components... + interceptPartition(({ message, compileRequest }) => { ++ // Island-only messages never trigger a full parent render on the server, ++ // so bound children can't receive fresh props from them. Bundling would ++ // only couple concurrent island requests together (stalling, for example, ++ // the second of two visible lazy island loads)... ++ if (! message.hasActionForComponent()) return ++ + let component = message.component + + let bundledMessages = [] +diff --git a/src/Features/SupportIslands/BrowserTest.php b/src/Features/SupportIslands/BrowserTest.php +index c4870c5e..e5254636 100644 +--- a/src/Features/SupportIslands/BrowserTest.php ++++ b/src/Features/SupportIslands/BrowserTest.php +@@ -1321,4 +1321,90 @@ class BrowserTest extends BrowserTestCase + ->assertDontSee('ENDISLAND') + ; + } ++ ++ public function test_visible_lazy_islands_with_a_reactive_nested_component_hydrate() ++ { ++ Livewire::visit([new class extends \Livewire\Component { ++ public bool $editing = false; ++ ++ public function toggle() ++ { ++ $this->editing = ! $this->editing; ++ } ++ ++ public function render() { ++ return <<<'HTML' ++
++ ++ @island(name: 'one', lazy: true, always: true) ++ @placeholder
Loading one
@endplaceholder ++
One mounted
++ @endisland ++ @island(name: 'two', lazy: true, always: true) ++ @placeholder
Loading two
@endplaceholder ++
Two mounted
++ @endisland ++ ++
++ HTML; ++ } ++ }, 'nested' => new class extends \Livewire\Component { ++ #[\Livewire\Attributes\Reactive] ++ public $editing; ++ public function render() { ++ return <<<'HTML' ++
{{ $editing ? 'Yes' : 'No' }}
++ HTML; ++ } ++ }]) ++ ->waitFor('@one-mounted') ++ ->waitFor('@two-mounted') ++ ->assertNotPresent('@one-placeholder') ++ ->assertNotPresent('@two-placeholder') ++ ->assertSeeIn('@edit-mode', 'No') ++ ->waitForLivewire()->click('@toggle') ++ ->assertSeeIn('@edit-mode', 'Yes'); ++ } ++ ++ public function test_visible_lazy_islands_with_a_modelable_nested_component_hydrate() ++ { ++ Livewire::visit([new class extends \Livewire\Component { ++ public string $body = ''; ++ ++ public function render() { ++ return <<<'HTML' ++
++
{{ $body }}
++ @island(name: 'one', lazy: true, always: true) ++ @placeholder
Loading one
@endplaceholder ++
One mounted
++ @endisland ++ @island(name: 'two', lazy: true, always: true) ++ @placeholder
Loading two
@endplaceholder ++
Two mounted
++ @endisland ++ ++
++ HTML; ++ } ++ }, 'nested' => new class extends \Livewire\Component { ++ #[\Livewire\Attributes\Modelable] ++ public $content; ++ public function render() { ++ return <<<'HTML' ++
++ ++
++ HTML; ++ } ++ }]) ++ ->waitFor('@one-mounted') ++ ->waitFor('@two-mounted') ++ ->assertNotPresent('@one-placeholder') ++ ->assertNotPresent('@two-placeholder') ++ ->assertSeeNothingIn('@content') ++ ->assertSeeNothingIn('@input') ++ ->type('@input', 'livewire') ++ ->waitForTextIn('@content', 'livewire'); ++ } + } diff --git a/tasks/livewire__livewire-10650/solution/solve.sh b/tasks/livewire__livewire-10650/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/livewire__livewire-10650/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/livewire__livewire-10650/task.toml b/tasks/livewire__livewire-10650/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..cfad729ece5b74d2e78cac66eaf8da4651989432 --- /dev/null +++ b/tasks/livewire__livewire-10650/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/livewire__livewire-10650" +description = "[4.x] Fix lazy island hydration with nested reactive/modelable children" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "livewire", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "livewire/livewire" +ref = "ca45880b4fa6f11a6f15681af3fdd8295e627d2c" +reference = "https://github.com/livewire/livewire/pull/10650" +source_access = "auto" +built_at = "2026-11-16T16:09:51.519186+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:70e8e4c4793d6de9ab3c764ecac406496c410a430340db6d932635c984829a3e" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-01T20:50:03Z" +diff_format = "unified" +context_files = [ + "js/request/interactions.js", + "src/Features/SupportIslands/BrowserTest.php", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 92 +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.393139+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:2f2390ae721f22e7f98bd9abe1ac36a2c5ceabeab50941900a30b050e923e548" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/livewire__livewire-10650/tests/capture.py b/tasks/livewire__livewire-10650/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/livewire__livewire-10650/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/livewire__livewire-10650/tests/instruction.md b/tasks/livewire__livewire-10650/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..43f4a907b58b4c6676f4d1704584134949c1cdf5 --- /dev/null +++ b/tasks/livewire__livewire-10650/tests/instruction.md @@ -0,0 +1,52 @@ +# Issue + +**Title:** [4.x] Fix lazy island hydration with nested reactive/modelable children + +## Description + +When a component renders multiple visible lazy islands alongside a nested child with a `#[Reactive]` (or `#[Modelable]`) property, only the first island hydrates — the rest are stuck on their loading placeholders forever. Without the nested child, all islands load fine. + +```blade +@island(name: 'one', lazy: true, always: true) + @placeholder
Loading one...
@endplaceholder +
One
+@endisland + +@island(name: 'two', lazy: true, always: true) + @placeholder
Loading two...
@endplaceholder +
Two
+@endisland + + {{-- child with a #[Reactive] prop --}} +``` + +Regression introduced by #10529. Minimized reproduction in #10644. + +## Findings + +- Each visible lazy island fires its own `__lazyLoadIsland` action, and island actions are scoped per-island — so islands `one` and `two` produce two separate pending messages *for the same component*. +- The reactive/modelable partition interceptor in `js/request/interactions.js` bundles a child `$commit` into any outgoing message whose component has bound children. Island one's message compiles into a request alongside the child `$commit`; island two's message then bundles the *same* child message, and the merge logic in `compileRequest` pulls island two into island one's request. +- That yields one request containing two messages for the same component. The response handler matches payloads to messages by component id, so each island message processes *both* payloads. Under the sequential island morph handling introduced in #10529, the second island's hydration never lands. +- The bundled child `$commit` is pure waste for island-only messages anyway: island calls skip the parent's full render on the server (`SupportIslands::call()` renders only the island, and `__lazyLoadIsland` returns early before ever touching component state), so the child stub is never re-rendered and its reactive props can't receive new values. + +## Potential solutions + +- **Skip child bundling for island-only messages** — a one-line guard reusing the existing `Message.hasActionForComponent()` helper. Fixes the whole class of stalls (concurrent lazy loads, island polls, island-scoped actions), not just lazy loading. +- Narrow the skip to `__lazyLoadIsland` calls only — but the same stall stays reachable through any two concurrent island-scoped messages (e.g. two polling islands). +- Rework the `compileRequest` merge logic so a request can never contain two messages for the same component — addresses the collision at its root but is more invasive, and island messages still shouldn't bundle children they can't update. + +## Proposed solution + +Skip reactive/modelable child bundling for island-only messages (`! message.hasActionForComponent()`). + +- Concurrent visible lazy islands hydrate independently again +- Normal component updates still bundle reactive/modelable children exactly as before (covered by the new tests' toggle/typing assertions) +- Existing island ordering behavior is untouched + +--- + +Note: with this change, actions fired from *inside* an island no longer sync reactive children in the same request. For children outside islands that sync was always a no-op render (the parent template never re-renders during an island request, so the child could never receive new prop values). A reactive child nested *inside* an island is the one case that loses live syncing — consistent with islands' scoped-render semantics, and previously untested. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `ca45880b4fa6`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10650/tests/oracle.patch b/tasks/livewire__livewire-10650/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..ae68022694607901330cae4935a49ac9fb2e2bb8 --- /dev/null +++ b/tasks/livewire__livewire-10650/tests/oracle.patch @@ -0,0 +1,112 @@ +diff --git a/js/request/interactions.js b/js/request/interactions.js +index 0f6ebd97..dd7068fe 100644 +--- a/js/request/interactions.js ++++ b/js/request/interactions.js +@@ -21,6 +21,12 @@ export function coordinateNetworkInteractions(messageBus) { + + // Handle modelable/reactive components... + interceptPartition(({ message, compileRequest }) => { ++ // Island-only messages never trigger a full parent render on the server, ++ // so bound children can't receive fresh props from them. Bundling would ++ // only couple concurrent island requests together (stalling, for example, ++ // the second of two visible lazy island loads)... ++ if (! message.hasActionForComponent()) return ++ + let component = message.component + + let bundledMessages = [] +diff --git a/src/Features/SupportIslands/BrowserTest.php b/src/Features/SupportIslands/BrowserTest.php +index c4870c5e..e5254636 100644 +--- a/src/Features/SupportIslands/BrowserTest.php ++++ b/src/Features/SupportIslands/BrowserTest.php +@@ -1321,4 +1321,90 @@ class BrowserTest extends BrowserTestCase + ->assertDontSee('ENDISLAND') + ; + } ++ ++ public function test_visible_lazy_islands_with_a_reactive_nested_component_hydrate() ++ { ++ Livewire::visit([new class extends \Livewire\Component { ++ public bool $editing = false; ++ ++ public function toggle() ++ { ++ $this->editing = ! $this->editing; ++ } ++ ++ public function render() { ++ return <<<'HTML' ++
++ ++ @island(name: 'one', lazy: true, always: true) ++ @placeholder
Loading one
@endplaceholder ++
One mounted
++ @endisland ++ @island(name: 'two', lazy: true, always: true) ++ @placeholder
Loading two
@endplaceholder ++
Two mounted
++ @endisland ++ ++
++ HTML; ++ } ++ }, 'nested' => new class extends \Livewire\Component { ++ #[\Livewire\Attributes\Reactive] ++ public $editing; ++ public function render() { ++ return <<<'HTML' ++
{{ $editing ? 'Yes' : 'No' }}
++ HTML; ++ } ++ }]) ++ ->waitFor('@one-mounted') ++ ->waitFor('@two-mounted') ++ ->assertNotPresent('@one-placeholder') ++ ->assertNotPresent('@two-placeholder') ++ ->assertSeeIn('@edit-mode', 'No') ++ ->waitForLivewire()->click('@toggle') ++ ->assertSeeIn('@edit-mode', 'Yes'); ++ } ++ ++ public function test_visible_lazy_islands_with_a_modelable_nested_component_hydrate() ++ { ++ Livewire::visit([new class extends \Livewire\Component { ++ public string $body = ''; ++ ++ public function render() { ++ return <<<'HTML' ++
++
{{ $body }}
++ @island(name: 'one', lazy: true, always: true) ++ @placeholder
Loading one
@endplaceholder ++
One mounted
++ @endisland ++ @island(name: 'two', lazy: true, always: true) ++ @placeholder
Loading two
@endplaceholder ++
Two mounted
++ @endisland ++ ++
++ HTML; ++ } ++ }, 'nested' => new class extends \Livewire\Component { ++ #[\Livewire\Attributes\Modelable] ++ public $content; ++ public function render() { ++ return <<<'HTML' ++
++ ++
++ HTML; ++ } ++ }]) ++ ->waitFor('@one-mounted') ++ ->waitFor('@two-mounted') ++ ->assertNotPresent('@one-placeholder') ++ ->assertNotPresent('@two-placeholder') ++ ->assertSeeNothingIn('@content') ++ ->assertSeeNothingIn('@input') ++ ->type('@input', 'livewire') ++ ->waitForTextIn('@content', 'livewire'); ++ } + } diff --git a/tasks/livewire__livewire-10650/tests/test.sh b/tasks/livewire__livewire-10650/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..258c8a6c568f5afa547527bd934751c2fdca02c9 --- /dev/null +++ b/tasks/livewire__livewire-10650/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace ca45880b4fa6f11a6f15681af3fdd8295e627d2c > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/livewire__livewire-10650/tests/verifier.py b/tasks/livewire__livewire-10650/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/livewire__livewire-10650/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/livewire__livewire-10653/environment/Dockerfile b/tasks/livewire__livewire-10653/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..43b1301d9cb20aa15d7a600e2d48b4d77088f6ab --- /dev/null +++ b/tasks/livewire__livewire-10653/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/livewire/livewire.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/livewire/livewire.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/livewire/livewire.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 7ee2e770d7d7efc23b558880bb64cb7be49870cd 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 7ee2e770d7d7efc23b558880bb64cb7be49870cd \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 7ee2e770d7d7efc23b558880bb64cb7be49870cd \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/livewire__livewire-10653/instruction.md b/tasks/livewire__livewire-10653/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..010fbdbf411baa62fe7a2cc0180f382c809b343c --- /dev/null +++ b/tasks/livewire__livewire-10653/instruction.md @@ -0,0 +1,25 @@ +# Issue + +**Title:** [4.x] Fix wire:navigate breaking when a teleport targets an element inside @persist + +## Description + +Clicking a `wire:navigate` link can leave the destination page completely inert. No Livewire, no Alpine, nothing until a manual refresh. It happens when a persisted element holds an `x-teleport` pointing at a target inside itself and the destination page ships no matching target, which is what you get when the persisted component is `#[Lazy]` and only its placeholder comes down. + +```blade +@persist('sidebar') +
+ + +@endpersist +``` + +`putPersistantElementsBack()` ran its put-back callback before re-attaching the persisted element, so `unPackPersistedTeleports()` resolved teleport targets through `document.querySelector()` while that element was still detached. The target could not be found, `placeInDom` threw on `null.appendChild(...)`, and since the exception escaped `swapCurrentPageWithNewHtml`, `nowInitializeAlpineOnTheNewPage` never ran. + +Every persisted element now goes back on the page first and the callbacks run afterwards, so a teleport can also resolve a target that lives inside a different persist. That also mirrors `storePersistantElementsForLater()`, which already packs up while the element is still attached. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `7ee2e770d7d7`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10653/solution/patch.diff b/tasks/livewire__livewire-10653/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..a2d79862b126995bd63a6d91ba3278e080a230cc --- /dev/null +++ b/tasks/livewire__livewire-10653/solution/patch.diff @@ -0,0 +1,172 @@ +diff --git a/js/plugins/navigate/persist.js b/js/plugins/navigate/persist.js +index edb65809..90c56664 100644 +--- a/js/plugins/navigate/persist.js ++++ b/js/plugins/navigate/persist.js +@@ -18,6 +18,7 @@ export function storePersistantElementsForLater(callback) { + + export function putPersistantElementsBack(callback) { + let usedPersists = [] ++ let putBacks = [] + + document.querySelectorAll('[x-persist]').forEach(i => { + let old = els[i.getAttribute('x-persist')] +@@ -29,13 +30,17 @@ export function putPersistantElementsBack(callback) { + + old._x_wasPersisted = true + +- callback(old, i) +- + Alpine.mutateDom(() => { + i.replaceWith(old) + }) ++ ++ putBacks.push([old, i]) + }) + ++ // Wait until every persisted element is back on the page before running the ++ // callbacks, otherwise a teleport can't resolve a target inside one of them... ++ putBacks.forEach(([old, i]) => callback(old, i)) ++ + Object.entries(els).forEach(([key, el]) => { + if (usedPersists.includes(key)) return + +diff --git a/js/plugins/navigate/teleport.js b/js/plugins/navigate/teleport.js +index 81eabd9f..fbc7f917 100644 +--- a/js/plugins/navigate/teleport.js ++++ b/js/plugins/navigate/teleport.js +@@ -17,7 +17,7 @@ export function removeAnyLeftOverStaleTeleportTargets(body) { + } + + export function unPackPersistedTeleports(persistedEl) { +- // Before we put back any persisted elements, we're going to ++ // Now that the persisted elements are back on the page, we're going to + // find any "x-teleports" and put their targets back on the page... + Alpine.walk(persistedEl, (el, skip) => { + if (! el._x_teleport) return; +diff --git a/src/Features/SupportNavigate/BrowserTest.php b/src/Features/SupportNavigate/BrowserTest.php +index 74ae0701..6e419ca0 100644 +--- a/src/Features/SupportNavigate/BrowserTest.php ++++ b/src/Features/SupportNavigate/BrowserTest.php +@@ -254,6 +254,122 @@ class BrowserTest extends \Tests\BrowserTestCase + ; + } + ++ public function test_navigate_works_with_teleports_targeting_inside_a_persist() ++ { ++ $this->registerComponentTestRoutes([ ++ '/second' => new class extends Component { ++ public function render(){ return <<<'HTML' ++
++
++ On second page ++
++ ++ @persist('header') ++
Placeholder
++ @endpersist ++
++ HTML; } ++ }, ++ ]); ++ ++ Livewire::visit(new class extends Component { ++ public function render(){ ++ return <<<'HTML' ++
++
++ On first page ++
++ ++ @persist('header') ++
++
++ ++ ++
++ @endpersist ++ ++ Go to second page ++
++ HTML; ++ } ++ }) ++ ->assertSeeIn('@target', '0') ++ ->click('@button') ++ ->assertSeeIn('@target', '1') ++ ->click('@link') ++ ->waitForText('On second page') ++ ->assertSeeIn('@target', '1') ++ ->click('@button') ++ ->assertSeeIn('@target', '2') ++ ; ++ } ++ ++ public function test_navigate_works_with_teleports_targeting_inside_another_persist() ++ { ++ $this->registerComponentTestRoutes([ ++ '/second' => new class extends Component { ++ public function render(){ return <<<'HTML' ++
++
++ On second page ++
++ ++ @persist('header') ++
Placeholder
++ @endpersist ++ ++ @persist('sidebar') ++
Placeholder
++ @endpersist ++
++ HTML; } ++ }, ++ ]); ++ ++ Livewire::visit(new class extends Component { ++ public function render(){ ++ return <<<'HTML' ++
++
++ On first page ++
++ ++ @persist('header') ++
++ ++
++ @endpersist ++ ++ @persist('sidebar') ++
++ @endpersist ++ ++ Go to second page ++
++ HTML; ++ } ++ }) ++ ->assertSeeIn('@target', '0') ++ ->click('@button') ++ ->assertSeeIn('@target', '1') ++ ->click('@link') ++ ->waitForText('On second page') ++ ->assertSeeIn('@target', '1') ++ ->click('@button') ++ ->assertSeeIn('@target', '2') ++ ; ++ } ++ + public function test_can_configure_progress_bar() + { + $this->browse(function ($browser) { diff --git a/tasks/livewire__livewire-10653/solution/solve.sh b/tasks/livewire__livewire-10653/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/livewire__livewire-10653/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/livewire__livewire-10653/task.toml b/tasks/livewire__livewire-10653/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..1274b0efed794589a63aa4e3e93fa731bab6bd4e --- /dev/null +++ b/tasks/livewire__livewire-10653/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/livewire__livewire-10653" +description = "[4.x] Fix wire:navigate breaking when a teleport targets an element inside @persist" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "livewire", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "livewire/livewire" +ref = "7ee2e770d7d7efc23b558880bb64cb7be49870cd" +reference = "https://github.com/livewire/livewire/pull/10653" +source_access = "auto" +built_at = "2026-11-16T16:09:51.517194+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:711c71a6ba8e75241616d613f8d3114195cafac1e014381e14788ef725ed08a0" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-03T11:52:29Z" +diff_format = "unified" +context_files = [ + "js/plugins/navigate/persist.js", + "js/plugins/navigate/teleport.js", + "src/Features/SupportNavigate/BrowserTest.php", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 127 +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.393999+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:2b0dd27bb3599be98d6d8a13e05d07418de77763e95a1834ed28ae230976e6c0" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/livewire__livewire-10653/tests/capture.py b/tasks/livewire__livewire-10653/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/livewire__livewire-10653/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/livewire__livewire-10653/tests/instruction.md b/tasks/livewire__livewire-10653/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..010fbdbf411baa62fe7a2cc0180f382c809b343c --- /dev/null +++ b/tasks/livewire__livewire-10653/tests/instruction.md @@ -0,0 +1,25 @@ +# Issue + +**Title:** [4.x] Fix wire:navigate breaking when a teleport targets an element inside @persist + +## Description + +Clicking a `wire:navigate` link can leave the destination page completely inert. No Livewire, no Alpine, nothing until a manual refresh. It happens when a persisted element holds an `x-teleport` pointing at a target inside itself and the destination page ships no matching target, which is what you get when the persisted component is `#[Lazy]` and only its placeholder comes down. + +```blade +@persist('sidebar') +
+ + +@endpersist +``` + +`putPersistantElementsBack()` ran its put-back callback before re-attaching the persisted element, so `unPackPersistedTeleports()` resolved teleport targets through `document.querySelector()` while that element was still detached. The target could not be found, `placeInDom` threw on `null.appendChild(...)`, and since the exception escaped `swapCurrentPageWithNewHtml`, `nowInitializeAlpineOnTheNewPage` never ran. + +Every persisted element now goes back on the page first and the callbacks run afterwards, so a teleport can also resolve a target that lives inside a different persist. That also mirrors `storePersistantElementsForLater()`, which already packs up while the element is still attached. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `7ee2e770d7d7`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10653/tests/oracle.patch b/tasks/livewire__livewire-10653/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..a2d79862b126995bd63a6d91ba3278e080a230cc --- /dev/null +++ b/tasks/livewire__livewire-10653/tests/oracle.patch @@ -0,0 +1,172 @@ +diff --git a/js/plugins/navigate/persist.js b/js/plugins/navigate/persist.js +index edb65809..90c56664 100644 +--- a/js/plugins/navigate/persist.js ++++ b/js/plugins/navigate/persist.js +@@ -18,6 +18,7 @@ export function storePersistantElementsForLater(callback) { + + export function putPersistantElementsBack(callback) { + let usedPersists = [] ++ let putBacks = [] + + document.querySelectorAll('[x-persist]').forEach(i => { + let old = els[i.getAttribute('x-persist')] +@@ -29,13 +30,17 @@ export function putPersistantElementsBack(callback) { + + old._x_wasPersisted = true + +- callback(old, i) +- + Alpine.mutateDom(() => { + i.replaceWith(old) + }) ++ ++ putBacks.push([old, i]) + }) + ++ // Wait until every persisted element is back on the page before running the ++ // callbacks, otherwise a teleport can't resolve a target inside one of them... ++ putBacks.forEach(([old, i]) => callback(old, i)) ++ + Object.entries(els).forEach(([key, el]) => { + if (usedPersists.includes(key)) return + +diff --git a/js/plugins/navigate/teleport.js b/js/plugins/navigate/teleport.js +index 81eabd9f..fbc7f917 100644 +--- a/js/plugins/navigate/teleport.js ++++ b/js/plugins/navigate/teleport.js +@@ -17,7 +17,7 @@ export function removeAnyLeftOverStaleTeleportTargets(body) { + } + + export function unPackPersistedTeleports(persistedEl) { +- // Before we put back any persisted elements, we're going to ++ // Now that the persisted elements are back on the page, we're going to + // find any "x-teleports" and put their targets back on the page... + Alpine.walk(persistedEl, (el, skip) => { + if (! el._x_teleport) return; +diff --git a/src/Features/SupportNavigate/BrowserTest.php b/src/Features/SupportNavigate/BrowserTest.php +index 74ae0701..6e419ca0 100644 +--- a/src/Features/SupportNavigate/BrowserTest.php ++++ b/src/Features/SupportNavigate/BrowserTest.php +@@ -254,6 +254,122 @@ class BrowserTest extends \Tests\BrowserTestCase + ; + } + ++ public function test_navigate_works_with_teleports_targeting_inside_a_persist() ++ { ++ $this->registerComponentTestRoutes([ ++ '/second' => new class extends Component { ++ public function render(){ return <<<'HTML' ++
++
++ On second page ++
++ ++ @persist('header') ++
Placeholder
++ @endpersist ++
++ HTML; } ++ }, ++ ]); ++ ++ Livewire::visit(new class extends Component { ++ public function render(){ ++ return <<<'HTML' ++
++
++ On first page ++
++ ++ @persist('header') ++
++
++ ++ ++
++ @endpersist ++ ++ Go to second page ++
++ HTML; ++ } ++ }) ++ ->assertSeeIn('@target', '0') ++ ->click('@button') ++ ->assertSeeIn('@target', '1') ++ ->click('@link') ++ ->waitForText('On second page') ++ ->assertSeeIn('@target', '1') ++ ->click('@button') ++ ->assertSeeIn('@target', '2') ++ ; ++ } ++ ++ public function test_navigate_works_with_teleports_targeting_inside_another_persist() ++ { ++ $this->registerComponentTestRoutes([ ++ '/second' => new class extends Component { ++ public function render(){ return <<<'HTML' ++
++
++ On second page ++
++ ++ @persist('header') ++
Placeholder
++ @endpersist ++ ++ @persist('sidebar') ++
Placeholder
++ @endpersist ++
++ HTML; } ++ }, ++ ]); ++ ++ Livewire::visit(new class extends Component { ++ public function render(){ ++ return <<<'HTML' ++
++
++ On first page ++
++ ++ @persist('header') ++
++ ++
++ @endpersist ++ ++ @persist('sidebar') ++
++ @endpersist ++ ++ Go to second page ++
++ HTML; ++ } ++ }) ++ ->assertSeeIn('@target', '0') ++ ->click('@button') ++ ->assertSeeIn('@target', '1') ++ ->click('@link') ++ ->waitForText('On second page') ++ ->assertSeeIn('@target', '1') ++ ->click('@button') ++ ->assertSeeIn('@target', '2') ++ ; ++ } ++ + public function test_can_configure_progress_bar() + { + $this->browse(function ($browser) { diff --git a/tasks/livewire__livewire-10653/tests/test.sh b/tasks/livewire__livewire-10653/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..44694a05f6bf1875597ac2a38ce5ad51ec97d5dd --- /dev/null +++ b/tasks/livewire__livewire-10653/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 7ee2e770d7d7efc23b558880bb64cb7be49870cd > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/livewire__livewire-10653/tests/verifier.py b/tasks/livewire__livewire-10653/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/livewire__livewire-10653/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/livewire__livewire-10656/environment/Dockerfile b/tasks/livewire__livewire-10656/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..43b1301d9cb20aa15d7a600e2d48b4d77088f6ab --- /dev/null +++ b/tasks/livewire__livewire-10656/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/livewire/livewire.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/livewire/livewire.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/livewire/livewire.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 7ee2e770d7d7efc23b558880bb64cb7be49870cd 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 7ee2e770d7d7efc23b558880bb64cb7be49870cd \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 7ee2e770d7d7efc23b558880bb64cb7be49870cd \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/livewire__livewire-10656/instruction.md b/tasks/livewire__livewire-10656/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c6611fddc8710134db96265e6d62e48a5baa7124 --- /dev/null +++ b/tasks/livewire__livewire-10656/instruction.md @@ -0,0 +1,28 @@ +# Issue + +**Title:** [4.x] Fix `$wire.$watch` crash from lazy placeholder node conflict + +## Description + +## The problem + +`$wire.$watch` ties its cleanup to the component, not the element calling it. Alpine's morph "clone" pass runs `x-data` `init()` on a throwaway node before diffing, with its reactivity neutered, this happens whenever a lazy placeholder shares node positions with its real markup. The resulting broken watcher gets stuck in `component.cleanups` and throws when the component is destroyed, aborting the rest of the cleanup and leaving the component registered in `window.Livewire.all()` forever. + +More details and reproduction here : #10655 + +## The fix + +Tie `$wire.$watch`'s cleanup to the calling element when possible, like `$wire.$entangle` already does. Direct usage (`@script`, file uploads) falls back to the component's lifetime, unchanged. Extracted into `js/features/supportWatch.js`. + +## Tests + +- [x] Added a regression test: lazy component, placeholder/real markup share node positions, `$wire.$watch` in `x-data` +- [x] Fails before the fix (same error), passes after +- [x] `SupportLazyLoading` (24 tests) pass +- [x] `SupportFileUploads` (10 tests) pass, no collision with file upload's own watcher cleanup +- [x] `JavascriptUnwatchBrowserTest` passes, manual unwatch from `x-data` still works +- [x] `SupportJsModules`/`SupportWireIntersect` failures are pre-existing on `4.x` (confirmed unrelated to this change) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `7ee2e770d7d7`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10656/solution/patch.diff b/tasks/livewire__livewire-10656/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..1d076f139731243f404d94f25a132755d9747cf5 --- /dev/null +++ b/tasks/livewire__livewire-10656/solution/patch.diff @@ -0,0 +1,121 @@ +diff --git a/js/$wire.js b/js/$wire.js +index 6909719a..b5e86f58 100644 +--- a/js/$wire.js ++++ b/js/$wire.js +@@ -1,6 +1,7 @@ + import { cancelUpload, removeUpload, upload, uploadMultiple } from './features/supportFileUploads' + import { dispatch, dispatchEl, dispatchRef, dispatchSelf, dispatchTo, listen } from '@/events' + import { generateEntangleFunction } from '@/features/supportEntangle' ++import { generateWatchFunction } from '@/features/supportWatch' + import { findComponentByEl } from '@/store' + import { dataGet, dataSet } from '@/utils' + import Alpine from 'alpinejs' +@@ -119,6 +120,8 @@ Alpine.magic('wire', (el, { cleanup }) => { + + if (['$entangle', 'entangle'].includes(property)) { + return generateEntangleFunction(component, cleanup) ++ } else if (['$watch', 'watch'].includes(property)) { ++ return generateWatchFunction(component, cleanup) + } + + return component.$wire[property] +@@ -277,18 +280,7 @@ wireProperty('$toggle', (component) => (name, live = true) => { + }) + + wireProperty('$watch', (component) => (path, callback) => { +- let getter = () => { +- return dataGet(component.reactive, path) +- } +- +- let unwatch = Alpine.watch(getter, callback) +- +- let removeCleanup = component.addCleanup(unwatch) +- +- return () => { +- removeCleanup() +- unwatch() +- } ++ return generateWatchFunction(component)(path, callback) + }) + + wireProperty('$effect', (component) => (callback) => { +diff --git a/js/features/supportWatch.js b/js/features/supportWatch.js +new file mode 100644 +index 00000000..6cfc4834 +--- /dev/null ++++ b/js/features/supportWatch.js +@@ -0,0 +1,23 @@ ++import { dataGet } from '@/utils' ++import Alpine from 'alpinejs' ++ ++export function generateWatchFunction(component, cleanup) { ++ return (path, callback) => { ++ let getter = () => dataGet(component.reactive, path) ++ ++ let unwatch = Alpine.watch(getter, callback) ++ ++ if (cleanup) { ++ cleanup(unwatch) ++ ++ return unwatch ++ } ++ ++ let removeCleanup = component.addCleanup(unwatch) ++ ++ return () => { ++ removeCleanup() ++ unwatch() ++ } ++ } ++} +diff --git a/src/Features/SupportLazyLoading/BrowserTest.php b/src/Features/SupportLazyLoading/BrowserTest.php +index b975527f..d1afc724 100644 +--- a/src/Features/SupportLazyLoading/BrowserTest.php ++++ b/src/Features/SupportLazyLoading/BrowserTest.php +@@ -827,6 +827,46 @@ class BrowserTest extends BrowserTestCase + ; + } + ++ public function test_conflicting_placeholder_node_does_not_break_watch_cleanup_or_leak_memory_on_lazy_component() ++ { ++ Livewire::visit([ ++ new class extends Component { ++ public bool $childShown = false; ++ ++ public function render() { return << ++ ++ ++ @if (\$this->childShown) ++ ++ @endif ++ ++ HTML; } ++ }, 'child' => new class extends Component { ++ public function placeholder() { return << ++
Loading...
++
Dummy placeholder
++ ++ HTML; } ++ ++ public function render() { return << ++
++ Children component ++
++ ++ HTML; } ++ } ++ ]) ++ ->waitForText('Toggle') ++ ->click('button') ++ ->waitForText('Children component') ++ ->click('button') ++ ->waitUntilMissing('#child') ++ ->assertConsoleLogHasNoErrors() ++ ->assertScript("window.Livewire.all().some(c => c.name === 'child')", false); ++ } + } + + class Page extends Component { diff --git a/tasks/livewire__livewire-10656/solution/solve.sh b/tasks/livewire__livewire-10656/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/livewire__livewire-10656/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/livewire__livewire-10656/task.toml b/tasks/livewire__livewire-10656/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..d322217f6dfc4fbd6fe94f1b8b09ac4410339849 --- /dev/null +++ b/tasks/livewire__livewire-10656/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/livewire__livewire-10656" +description = "[4.x] Fix `$wire.$watch` crash from lazy placeholder node conflict" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "livewire", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "livewire/livewire" +ref = "7ee2e770d7d7efc23b558880bb64cb7be49870cd" +reference = "https://github.com/livewire/livewire/pull/10656" +source_access = "auto" +built_at = "2026-11-16T16:09:51.513548+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:3871101d5b35535c238827f9b32e480262d5ce1fbd4b1847a19a4541293bbe50" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-03T12:00:09Z" +diff_format = "unified" +context_files = [ + "js/$wire.js", + "js/features/supportWatch.js", + "src/Features/SupportLazyLoading/BrowserTest.php", +] +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.396959+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:2b0dd27bb3599be98d6d8a13e05d07418de77763e95a1834ed28ae230976e6c0" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/livewire__livewire-10656/tests/capture.py b/tasks/livewire__livewire-10656/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/livewire__livewire-10656/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/livewire__livewire-10656/tests/instruction.md b/tasks/livewire__livewire-10656/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c6611fddc8710134db96265e6d62e48a5baa7124 --- /dev/null +++ b/tasks/livewire__livewire-10656/tests/instruction.md @@ -0,0 +1,28 @@ +# Issue + +**Title:** [4.x] Fix `$wire.$watch` crash from lazy placeholder node conflict + +## Description + +## The problem + +`$wire.$watch` ties its cleanup to the component, not the element calling it. Alpine's morph "clone" pass runs `x-data` `init()` on a throwaway node before diffing, with its reactivity neutered, this happens whenever a lazy placeholder shares node positions with its real markup. The resulting broken watcher gets stuck in `component.cleanups` and throws when the component is destroyed, aborting the rest of the cleanup and leaving the component registered in `window.Livewire.all()` forever. + +More details and reproduction here : #10655 + +## The fix + +Tie `$wire.$watch`'s cleanup to the calling element when possible, like `$wire.$entangle` already does. Direct usage (`@script`, file uploads) falls back to the component's lifetime, unchanged. Extracted into `js/features/supportWatch.js`. + +## Tests + +- [x] Added a regression test: lazy component, placeholder/real markup share node positions, `$wire.$watch` in `x-data` +- [x] Fails before the fix (same error), passes after +- [x] `SupportLazyLoading` (24 tests) pass +- [x] `SupportFileUploads` (10 tests) pass, no collision with file upload's own watcher cleanup +- [x] `JavascriptUnwatchBrowserTest` passes, manual unwatch from `x-data` still works +- [x] `SupportJsModules`/`SupportWireIntersect` failures are pre-existing on `4.x` (confirmed unrelated to this change) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `7ee2e770d7d7`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10656/tests/oracle.patch b/tasks/livewire__livewire-10656/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..1d076f139731243f404d94f25a132755d9747cf5 --- /dev/null +++ b/tasks/livewire__livewire-10656/tests/oracle.patch @@ -0,0 +1,121 @@ +diff --git a/js/$wire.js b/js/$wire.js +index 6909719a..b5e86f58 100644 +--- a/js/$wire.js ++++ b/js/$wire.js +@@ -1,6 +1,7 @@ + import { cancelUpload, removeUpload, upload, uploadMultiple } from './features/supportFileUploads' + import { dispatch, dispatchEl, dispatchRef, dispatchSelf, dispatchTo, listen } from '@/events' + import { generateEntangleFunction } from '@/features/supportEntangle' ++import { generateWatchFunction } from '@/features/supportWatch' + import { findComponentByEl } from '@/store' + import { dataGet, dataSet } from '@/utils' + import Alpine from 'alpinejs' +@@ -119,6 +120,8 @@ Alpine.magic('wire', (el, { cleanup }) => { + + if (['$entangle', 'entangle'].includes(property)) { + return generateEntangleFunction(component, cleanup) ++ } else if (['$watch', 'watch'].includes(property)) { ++ return generateWatchFunction(component, cleanup) + } + + return component.$wire[property] +@@ -277,18 +280,7 @@ wireProperty('$toggle', (component) => (name, live = true) => { + }) + + wireProperty('$watch', (component) => (path, callback) => { +- let getter = () => { +- return dataGet(component.reactive, path) +- } +- +- let unwatch = Alpine.watch(getter, callback) +- +- let removeCleanup = component.addCleanup(unwatch) +- +- return () => { +- removeCleanup() +- unwatch() +- } ++ return generateWatchFunction(component)(path, callback) + }) + + wireProperty('$effect', (component) => (callback) => { +diff --git a/js/features/supportWatch.js b/js/features/supportWatch.js +new file mode 100644 +index 00000000..6cfc4834 +--- /dev/null ++++ b/js/features/supportWatch.js +@@ -0,0 +1,23 @@ ++import { dataGet } from '@/utils' ++import Alpine from 'alpinejs' ++ ++export function generateWatchFunction(component, cleanup) { ++ return (path, callback) => { ++ let getter = () => dataGet(component.reactive, path) ++ ++ let unwatch = Alpine.watch(getter, callback) ++ ++ if (cleanup) { ++ cleanup(unwatch) ++ ++ return unwatch ++ } ++ ++ let removeCleanup = component.addCleanup(unwatch) ++ ++ return () => { ++ removeCleanup() ++ unwatch() ++ } ++ } ++} +diff --git a/src/Features/SupportLazyLoading/BrowserTest.php b/src/Features/SupportLazyLoading/BrowserTest.php +index b975527f..d1afc724 100644 +--- a/src/Features/SupportLazyLoading/BrowserTest.php ++++ b/src/Features/SupportLazyLoading/BrowserTest.php +@@ -827,6 +827,46 @@ class BrowserTest extends BrowserTestCase + ; + } + ++ public function test_conflicting_placeholder_node_does_not_break_watch_cleanup_or_leak_memory_on_lazy_component() ++ { ++ Livewire::visit([ ++ new class extends Component { ++ public bool $childShown = false; ++ ++ public function render() { return << ++ ++ ++ @if (\$this->childShown) ++ ++ @endif ++ ++ HTML; } ++ }, 'child' => new class extends Component { ++ public function placeholder() { return << ++
Loading...
++
Dummy placeholder
++ ++ HTML; } ++ ++ public function render() { return << ++
++ Children component ++
++ ++ HTML; } ++ } ++ ]) ++ ->waitForText('Toggle') ++ ->click('button') ++ ->waitForText('Children component') ++ ->click('button') ++ ->waitUntilMissing('#child') ++ ->assertConsoleLogHasNoErrors() ++ ->assertScript("window.Livewire.all().some(c => c.name === 'child')", false); ++ } + } + + class Page extends Component { diff --git a/tasks/livewire__livewire-10656/tests/test.sh b/tasks/livewire__livewire-10656/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..44694a05f6bf1875597ac2a38ce5ad51ec97d5dd --- /dev/null +++ b/tasks/livewire__livewire-10656/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 7ee2e770d7d7efc23b558880bb64cb7be49870cd > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/livewire__livewire-10656/tests/verifier.py b/tasks/livewire__livewire-10656/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/livewire__livewire-10656/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/livewire__livewire-10659/environment/Dockerfile b/tasks/livewire__livewire-10659/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..43b1301d9cb20aa15d7a600e2d48b4d77088f6ab --- /dev/null +++ b/tasks/livewire__livewire-10659/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/livewire/livewire.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/livewire/livewire.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/livewire/livewire.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 7ee2e770d7d7efc23b558880bb64cb7be49870cd 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 7ee2e770d7d7efc23b558880bb64cb7be49870cd \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 7ee2e770d7d7efc23b558880bb64cb7be49870cd \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/livewire__livewire-10659/instruction.md b/tasks/livewire__livewire-10659/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..05d7c959ebe2e64555750af4d7983ef3960b7708 --- /dev/null +++ b/tasks/livewire__livewire-10659/instruction.md @@ -0,0 +1,38 @@ +# Issue + +**Title:** [4.x] Keep children mounted during an island render + +## Description + +A `` mounted during an island render never makes it into the parent's `children` memo. The next ordinary render of the parent treats those children as if they had never rendered, mounts them again with new ids and full HTML, and the morph throws away the live components along with their state. + +An island-scoped action (`wire:island`, `wire:island.append`, `$wire.$island(...)`) calls `skipRender()` and renders only the island. Children mounted inside that island push themselves into the parent's `children` store as usual, and then dehydrate discards them: + +```php +function dehydrate($context) +{ + if ($this->component->shouldSkipRender()) { + $this->keepRenderedChildren(); // children = previousChildren + } + ... + $context->addMemo('children', $this->getChildren()); +} +``` + +`keepRenderedChildren()` was written for `#[Renderless]`, where nothing can have been mounted, so overwriting was safe. With islands it drops whatever the island just mounted. + +The practical cost is that `wire:island.append` can't be used for infinite scroll when the appended rows are components: every append works, and then the next render of the parent rebuilds all of them. + +The fix keeps the previously rendered children and layers this request's children over the top, so an entry mounted during the island render survives and a key rendered in both requests still resolves to the newer child. + +Two notes on the details: + +`array_replace` rather than the `array_merge` suggested in the issue. `array_merge` renumbers integer-like keys, and a numeric `wire:key` reaches this array as a real integer key, so merging turns keys `[1, 2]` into `[0, 1]` and breaks the lookup for every numeric-keyed child, including ones that work today. `array_replace` preserves the keys. + +This covers append mode, which is what the issue reports. Morph-mode islands lose children too, but for a different reason: `SupportNestingComponents` is registered ahead of `SupportIslands`, so the children memo is written before `SupportIslands::dehydrate()` runs `renderImplicitIslandMorphs()`, which is where morph children mount. That looks fixable by re-adding the memo after the morph render, and it passes the suite locally, but it's a separate cause and touches hook ordering, so I left it out rather than widen this PR. Happy to add it here or open a follow-up, whichever you prefer. + +Reported and diagnosed in #10657, along with the proposed fix. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `7ee2e770d7d7`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10659/solution/patch.diff b/tasks/livewire__livewire-10659/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..c7f35a3b2bb7a7af33f5a55942a86ff054fa26fe --- /dev/null +++ b/tasks/livewire__livewire-10659/solution/patch.diff @@ -0,0 +1,84 @@ +diff --git a/src/Features/SupportIslands/UnitTest.php b/src/Features/SupportIslands/UnitTest.php +index 9e37a50b..fe7374a0 100644 +--- a/src/Features/SupportIslands/UnitTest.php ++++ b/src/Features/SupportIslands/UnitTest.php +@@ -677,4 +677,66 @@ class UnitTest extends TestCase + + File::deleteDirectory($compiledPath); + } ++ ++ public function test_children_mounted_during_an_island_render_are_kept_in_the_children_memo() ++ { ++ Livewire::component('island-child', new class extends \Livewire\Component { ++ public $number = 0; ++ ++ public function render() { ++ return '
child {{ $number }}
'; ++ } ++ }); ++ ++ $component = Livewire::test(new class extends \Livewire\Component { ++ public $from = 1; ++ public $to = 1; ++ ++ public function loadMore() ++ { ++ $this->from = $this->to + 1; ++ $this->to++; ++ } ++ ++ public function render() { ++ return <<<'HTML' ++
++ @island(name: 'rows', always: true) ++ @foreach (range($from, $to) as $number) ++ ++ @endforeach ++ @endisland ++
++ HTML; ++ } ++ }); ++ ++ $this->assertSame(['row-1'], array_keys($component->snapshot['memo']['children'])); ++ ++ // Simulate an append-mode island render, like a "load more" button would... ++ $component->update(calls: [ ++ [ ++ 'method' => 'loadMore', ++ 'params' => [], ++ 'path' => '', ++ 'metadata' => [ ++ 'island' => [ ++ 'name' => 'rows', ++ 'mode' => 'append', ++ ], ++ ], ++ ], ++ ]); ++ ++ $this->assertSame(['row-1', 'row-2'], array_keys($component->snapshot['memo']['children'])); ++ ++ $appendedChildId = $component->snapshot['memo']['children']['row-2'][1]; ++ ++ $component->call('$refresh'); ++ ++ // The appended child should come back as a stub, not mount again from scratch... ++ $this->assertStringContainsString('wire:id="'.$appendedChildId.'" wire:name="island-child" wire:key="row-2"', $component->html()); ++ $this->assertStringNotContainsString('child 1', $component->html()); ++ $this->assertStringNotContainsString('child 2', $component->html()); ++ } + } +diff --git a/src/Features/SupportNestingComponents/SupportNestingComponents.php b/src/Features/SupportNestingComponents/SupportNestingComponents.php +index 8c19d84e..f299901d 100644 +--- a/src/Features/SupportNestingComponents/SupportNestingComponents.php ++++ b/src/Features/SupportNestingComponents/SupportNestingComponents.php +@@ -112,7 +112,7 @@ class SupportNestingComponents extends ComponentHook + + function keepRenderedChildren() + { +- $this->storeSet('children', $this->storeGet('previousChildren')); ++ $this->storeSet('children', array_replace($this->storeGet('previousChildren', []), $this->getChildren())); + } + + static function setParametersToMatchingProperties($component, $params) diff --git a/tasks/livewire__livewire-10659/solution/solve.sh b/tasks/livewire__livewire-10659/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/livewire__livewire-10659/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/livewire__livewire-10659/task.toml b/tasks/livewire__livewire-10659/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..fb2371bb135ccf2c421d418988ca1cd67260e775 --- /dev/null +++ b/tasks/livewire__livewire-10659/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/livewire__livewire-10659" +description = "[4.x] Keep children mounted during an island render" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "livewire", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "livewire/livewire" +ref = "7ee2e770d7d7efc23b558880bb64cb7be49870cd" +reference = "https://github.com/livewire/livewire/pull/10659" +source_access = "auto" +built_at = "2026-11-16T16:09:51.515390+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:004799865b26d07284cbf3e82f5a510534b48439770ca3021d1a839de10c839b" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-03T11:59:19Z" +diff_format = "unified" +context_files = [ + "src/Features/SupportIslands/UnitTest.php", + "src/Features/SupportNestingComponents/SupportNestingComponents.php", +] +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.398140+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:2b0dd27bb3599be98d6d8a13e05d07418de77763e95a1834ed28ae230976e6c0" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/livewire__livewire-10659/tests/capture.py b/tasks/livewire__livewire-10659/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/livewire__livewire-10659/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/livewire__livewire-10659/tests/instruction.md b/tasks/livewire__livewire-10659/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..05d7c959ebe2e64555750af4d7983ef3960b7708 --- /dev/null +++ b/tasks/livewire__livewire-10659/tests/instruction.md @@ -0,0 +1,38 @@ +# Issue + +**Title:** [4.x] Keep children mounted during an island render + +## Description + +A `` mounted during an island render never makes it into the parent's `children` memo. The next ordinary render of the parent treats those children as if they had never rendered, mounts them again with new ids and full HTML, and the morph throws away the live components along with their state. + +An island-scoped action (`wire:island`, `wire:island.append`, `$wire.$island(...)`) calls `skipRender()` and renders only the island. Children mounted inside that island push themselves into the parent's `children` store as usual, and then dehydrate discards them: + +```php +function dehydrate($context) +{ + if ($this->component->shouldSkipRender()) { + $this->keepRenderedChildren(); // children = previousChildren + } + ... + $context->addMemo('children', $this->getChildren()); +} +``` + +`keepRenderedChildren()` was written for `#[Renderless]`, where nothing can have been mounted, so overwriting was safe. With islands it drops whatever the island just mounted. + +The practical cost is that `wire:island.append` can't be used for infinite scroll when the appended rows are components: every append works, and then the next render of the parent rebuilds all of them. + +The fix keeps the previously rendered children and layers this request's children over the top, so an entry mounted during the island render survives and a key rendered in both requests still resolves to the newer child. + +Two notes on the details: + +`array_replace` rather than the `array_merge` suggested in the issue. `array_merge` renumbers integer-like keys, and a numeric `wire:key` reaches this array as a real integer key, so merging turns keys `[1, 2]` into `[0, 1]` and breaks the lookup for every numeric-keyed child, including ones that work today. `array_replace` preserves the keys. + +This covers append mode, which is what the issue reports. Morph-mode islands lose children too, but for a different reason: `SupportNestingComponents` is registered ahead of `SupportIslands`, so the children memo is written before `SupportIslands::dehydrate()` runs `renderImplicitIslandMorphs()`, which is where morph children mount. That looks fixable by re-adding the memo after the morph render, and it passes the suite locally, but it's a separate cause and touches hook ordering, so I left it out rather than widen this PR. Happy to add it here or open a follow-up, whichever you prefer. + +Reported and diagnosed in #10657, along with the proposed fix. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `7ee2e770d7d7`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10659/tests/oracle.patch b/tasks/livewire__livewire-10659/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..c7f35a3b2bb7a7af33f5a55942a86ff054fa26fe --- /dev/null +++ b/tasks/livewire__livewire-10659/tests/oracle.patch @@ -0,0 +1,84 @@ +diff --git a/src/Features/SupportIslands/UnitTest.php b/src/Features/SupportIslands/UnitTest.php +index 9e37a50b..fe7374a0 100644 +--- a/src/Features/SupportIslands/UnitTest.php ++++ b/src/Features/SupportIslands/UnitTest.php +@@ -677,4 +677,66 @@ class UnitTest extends TestCase + + File::deleteDirectory($compiledPath); + } ++ ++ public function test_children_mounted_during_an_island_render_are_kept_in_the_children_memo() ++ { ++ Livewire::component('island-child', new class extends \Livewire\Component { ++ public $number = 0; ++ ++ public function render() { ++ return '
child {{ $number }}
'; ++ } ++ }); ++ ++ $component = Livewire::test(new class extends \Livewire\Component { ++ public $from = 1; ++ public $to = 1; ++ ++ public function loadMore() ++ { ++ $this->from = $this->to + 1; ++ $this->to++; ++ } ++ ++ public function render() { ++ return <<<'HTML' ++
++ @island(name: 'rows', always: true) ++ @foreach (range($from, $to) as $number) ++ ++ @endforeach ++ @endisland ++
++ HTML; ++ } ++ }); ++ ++ $this->assertSame(['row-1'], array_keys($component->snapshot['memo']['children'])); ++ ++ // Simulate an append-mode island render, like a "load more" button would... ++ $component->update(calls: [ ++ [ ++ 'method' => 'loadMore', ++ 'params' => [], ++ 'path' => '', ++ 'metadata' => [ ++ 'island' => [ ++ 'name' => 'rows', ++ 'mode' => 'append', ++ ], ++ ], ++ ], ++ ]); ++ ++ $this->assertSame(['row-1', 'row-2'], array_keys($component->snapshot['memo']['children'])); ++ ++ $appendedChildId = $component->snapshot['memo']['children']['row-2'][1]; ++ ++ $component->call('$refresh'); ++ ++ // The appended child should come back as a stub, not mount again from scratch... ++ $this->assertStringContainsString('wire:id="'.$appendedChildId.'" wire:name="island-child" wire:key="row-2"', $component->html()); ++ $this->assertStringNotContainsString('child 1', $component->html()); ++ $this->assertStringNotContainsString('child 2', $component->html()); ++ } + } +diff --git a/src/Features/SupportNestingComponents/SupportNestingComponents.php b/src/Features/SupportNestingComponents/SupportNestingComponents.php +index 8c19d84e..f299901d 100644 +--- a/src/Features/SupportNestingComponents/SupportNestingComponents.php ++++ b/src/Features/SupportNestingComponents/SupportNestingComponents.php +@@ -112,7 +112,7 @@ class SupportNestingComponents extends ComponentHook + + function keepRenderedChildren() + { +- $this->storeSet('children', $this->storeGet('previousChildren')); ++ $this->storeSet('children', array_replace($this->storeGet('previousChildren', []), $this->getChildren())); + } + + static function setParametersToMatchingProperties($component, $params) diff --git a/tasks/livewire__livewire-10659/tests/test.sh b/tasks/livewire__livewire-10659/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..44694a05f6bf1875597ac2a38ce5ad51ec97d5dd --- /dev/null +++ b/tasks/livewire__livewire-10659/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 7ee2e770d7d7efc23b558880bb64cb7be49870cd > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/livewire__livewire-10659/tests/verifier.py b/tasks/livewire__livewire-10659/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/livewire__livewire-10659/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/livewire__livewire-10664/environment/Dockerfile b/tasks/livewire__livewire-10664/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..9ddf6d2977c1c4a40d7fdd40eef22f5f97f91531 --- /dev/null +++ b/tasks/livewire__livewire-10664/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/livewire/livewire.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/livewire/livewire.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/livewire/livewire.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 432402aaced5ce1d7df794e93017f82abb16266f 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 432402aaced5ce1d7df794e93017f82abb16266f \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 432402aaced5ce1d7df794e93017f82abb16266f \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/livewire__livewire-10664/instruction.md b/tasks/livewire__livewire-10664/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d292f84f21c7a91d0a07f876eaf1a93d66546215 --- /dev/null +++ b/tasks/livewire__livewire-10664/instruction.md @@ -0,0 +1,61 @@ +# Issue + +**Title:** [4.x] Allow custom x-cloak variants by targeting empty x-cloak attributes + +## Description + +## What does this PR do? + +This PR changes Livewire's default `x-cloak` CSS selector from: + +```css +[x-cloak] { + display: none !important; +} +``` + +to: + +```css +[x-cloak=""] { + display: none !important; +} +``` + +## Why is this needed? + +The current `[x-cloak]` selector matches any element containing the `x-cloak` attribute, regardless of its value. This makes it impossible to introduce value-based `x-cloak` variants without Livewire's default style also applying to them. + +For example, an application may want to cloak an element only below a specific responsive breakpoint: + +```html +
+ ... +
+``` + +```css +@media (width < theme(--breakpoint-lg)) { + [x-cloak="lg"] { + display: none !important; + } +} +``` + +With Livewire's current `[x-cloak]` rule, `x-cloak="lg"` is always hidden until Alpine initializes, including on screens at or above the `lg` breakpoint. This defeats the purpose of the responsive variant. + +Using `[x-cloak=""]` restricts Livewire's default style to the standard empty `x-cloak` attribute: + +```html +
+ ... +
+``` + +It therefore preserves the existing behavior for regular `x-cloak` usage while allowing applications to define their own value-based variants such as `x-cloak="lg"`. + +Alpine still removes the `x-cloak` attribute normally when it initializes, regardless of its value, so this change only makes Livewire's CSS selector more specific and extensible. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `432402aaced5`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10664/solution/patch.diff b/tasks/livewire__livewire-10664/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..cecef1cbb72ea6a999659a389e0c7d35e904295d --- /dev/null +++ b/tasks/livewire__livewire-10664/solution/patch.diff @@ -0,0 +1,18 @@ +diff --git a/src/Mechanisms/FrontendAssets/FrontendAssets.php b/src/Mechanisms/FrontendAssets/FrontendAssets.php +index ef4d3175..172797b2 100644 +--- a/src/Mechanisms/FrontendAssets/FrontendAssets.php ++++ b/src/Mechanisms/FrontendAssets/FrontendAssets.php +@@ -141,11 +141,11 @@ class FrontendAssets extends Mechanism + --livewire-progress-bar-color: {$progressBarColor}; + } + +- [x-cloak] { ++ [x-cloak=""] { + display: none !important; + } + +- [wire\:cloak] { ++ [wire\:cloak=""] { + display: none !important; + } + diff --git a/tasks/livewire__livewire-10664/solution/solve.sh b/tasks/livewire__livewire-10664/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/livewire__livewire-10664/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/livewire__livewire-10664/task.toml b/tasks/livewire__livewire-10664/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..182aa9295e1914291ceeb754cc4a7ae642c1a94c --- /dev/null +++ b/tasks/livewire__livewire-10664/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/livewire__livewire-10664" +description = "[4.x] Allow custom x-cloak variants by targeting empty x-cloak attributes" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "livewire", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "livewire/livewire" +ref = "432402aaced5ce1d7df794e93017f82abb16266f" +reference = "https://github.com/livewire/livewire/pull/10664" +source_access = "auto" +built_at = "2026-11-16T16:09:51.509009+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:88c2ac766a4887749c7454f032513ba0d693414f28483f48fbadaace5c0184f9" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-07T12:12:25Z" +diff_format = "unified" +context_files = [ + "src/Mechanisms/FrontendAssets/FrontendAssets.php", +] +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.406179+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:fc5cb2e2b79ba6e721f2e6c50b1acb53cb34635fac6249e17e0d15f6d040bd20" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/livewire__livewire-10664/tests/capture.py b/tasks/livewire__livewire-10664/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/livewire__livewire-10664/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/livewire__livewire-10664/tests/instruction.md b/tasks/livewire__livewire-10664/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d292f84f21c7a91d0a07f876eaf1a93d66546215 --- /dev/null +++ b/tasks/livewire__livewire-10664/tests/instruction.md @@ -0,0 +1,61 @@ +# Issue + +**Title:** [4.x] Allow custom x-cloak variants by targeting empty x-cloak attributes + +## Description + +## What does this PR do? + +This PR changes Livewire's default `x-cloak` CSS selector from: + +```css +[x-cloak] { + display: none !important; +} +``` + +to: + +```css +[x-cloak=""] { + display: none !important; +} +``` + +## Why is this needed? + +The current `[x-cloak]` selector matches any element containing the `x-cloak` attribute, regardless of its value. This makes it impossible to introduce value-based `x-cloak` variants without Livewire's default style also applying to them. + +For example, an application may want to cloak an element only below a specific responsive breakpoint: + +```html +
+ ... +
+``` + +```css +@media (width < theme(--breakpoint-lg)) { + [x-cloak="lg"] { + display: none !important; + } +} +``` + +With Livewire's current `[x-cloak]` rule, `x-cloak="lg"` is always hidden until Alpine initializes, including on screens at or above the `lg` breakpoint. This defeats the purpose of the responsive variant. + +Using `[x-cloak=""]` restricts Livewire's default style to the standard empty `x-cloak` attribute: + +```html +
+ ... +
+``` + +It therefore preserves the existing behavior for regular `x-cloak` usage while allowing applications to define their own value-based variants such as `x-cloak="lg"`. + +Alpine still removes the `x-cloak` attribute normally when it initializes, regardless of its value, so this change only makes Livewire's CSS selector more specific and extensible. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `432402aaced5`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10664/tests/oracle.patch b/tasks/livewire__livewire-10664/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..cecef1cbb72ea6a999659a389e0c7d35e904295d --- /dev/null +++ b/tasks/livewire__livewire-10664/tests/oracle.patch @@ -0,0 +1,18 @@ +diff --git a/src/Mechanisms/FrontendAssets/FrontendAssets.php b/src/Mechanisms/FrontendAssets/FrontendAssets.php +index ef4d3175..172797b2 100644 +--- a/src/Mechanisms/FrontendAssets/FrontendAssets.php ++++ b/src/Mechanisms/FrontendAssets/FrontendAssets.php +@@ -141,11 +141,11 @@ class FrontendAssets extends Mechanism + --livewire-progress-bar-color: {$progressBarColor}; + } + +- [x-cloak] { ++ [x-cloak=""] { + display: none !important; + } + +- [wire\:cloak] { ++ [wire\:cloak=""] { + display: none !important; + } + diff --git a/tasks/livewire__livewire-10664/tests/test.sh b/tasks/livewire__livewire-10664/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..35d3a64313dc70b599af571dd36eec63c56df89f --- /dev/null +++ b/tasks/livewire__livewire-10664/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 432402aaced5ce1d7df794e93017f82abb16266f > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/livewire__livewire-10664/tests/verifier.py b/tasks/livewire__livewire-10664/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/livewire__livewire-10664/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/livewire__livewire-10666/environment/Dockerfile b/tasks/livewire__livewire-10666/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..9ddf6d2977c1c4a40d7fdd40eef22f5f97f91531 --- /dev/null +++ b/tasks/livewire__livewire-10666/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/livewire/livewire.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/livewire/livewire.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/livewire/livewire.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 432402aaced5ce1d7df794e93017f82abb16266f 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 432402aaced5ce1d7df794e93017f82abb16266f \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 432402aaced5ce1d7df794e93017f82abb16266f \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/livewire__livewire-10666/instruction.md b/tasks/livewire__livewire-10666/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..56a988586ee2f014460da9c0e1671c66d4b17c1a --- /dev/null +++ b/tasks/livewire__livewire-10666/instruction.md @@ -0,0 +1,18 @@ +# Issue + +**Title:** [4.x] Fix @assets inside implicitly rendered islands not shipping + +## Description + +`@assets` inside an implicitly rendered island (deferred, lazy, `skip` + `wire:intersect`, or any `wire:*` action fired from inside an island) stopped shipping after #10529 batched implicit island morphs into `SupportIslands::dehydrate()`. `SupportScriptsAndAssets` is registered earlier in the service provider, so its `dehydrate()` already copies the component's asset store into the response before the island actually renders and pushes its `@assets` block. + +This adds a `before('dehydrate', ...)` hook from `SupportIslands::provide()` that flushes queued implicit island renders ahead of every other feature's `dehydrate()`, regardless of registration order, so the pushed assets are already in the store by the time they're collected. An explicit `$this->renderIsland()` call from an action runs synchronously during the action itself, so it was never affected and stays unaffected. + +Verification: +- Focused SupportIslands unit suite: 27 tests, 54 assertions +- Focused SupportIslands + SupportScriptsAndAssets browser suites: 53 tests +- Full unit suite: 1462 tests + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `432402aaced5`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10666/solution/patch.diff b/tasks/livewire__livewire-10666/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..bf36869b2f53f108467679fd85da8b9fc54b3cbe --- /dev/null +++ b/tasks/livewire__livewire-10666/solution/patch.diff @@ -0,0 +1,105 @@ +diff --git a/src/Features/SupportIslands/SupportIslands.php b/src/Features/SupportIslands/SupportIslands.php +index 5c128ddf..d68b6c56 100644 +--- a/src/Features/SupportIslands/SupportIslands.php ++++ b/src/Features/SupportIslands/SupportIslands.php +@@ -6,12 +6,19 @@ use Livewire\Features\SupportIslands\Compiler\IslandCompiler; + use Illuminate\Support\Facades\Blade; + use Livewire\ComponentHook; + ++use function Livewire\before; ++ + class SupportIslands extends ComponentHook + { + public static function provide() + { + static::registerInlineIslandPrecompiler(); + static::registerIslandDirective(); ++ ++ // Flush implicit island renders before any dehydrate hook, so other hooks (e.g. assets) see their output... ++ before('dehydrate', function ($component) { ++ $component->renderImplicitIslandMorphs(); ++ }); + } + + public static function registerIslandDirective() +diff --git a/src/Features/SupportIslands/UnitTest.php b/src/Features/SupportIslands/UnitTest.php +index fe7374a0..8438a0eb 100644 +--- a/src/Features/SupportIslands/UnitTest.php ++++ b/src/Features/SupportIslands/UnitTest.php +@@ -5,6 +5,7 @@ namespace Livewire\Features\SupportIslands; + use Tests\TestCase; + use Livewire\Livewire; + use Livewire\Features\SupportIslands\Compiler\IslandCompiler; ++use Livewire\Features\SupportScriptsAndAssets\SupportScriptsAndAssets; + use Illuminate\Support\Facades\File; + + class UnitTest extends TestCase +@@ -739,4 +740,68 @@ class UnitTest extends TestCase + $this->assertStringNotContainsString('child 1', $component->html()); + $this->assertStringNotContainsString('child 2', $component->html()); + } ++ ++ public function test_assets_inside_an_implicitly_rendered_island_are_shipped() ++ { ++ $component = Livewire::test(new class extends \Livewire\Component { ++ public function render() { ++ return <<<'HTML' ++
++ @island(defer: true) ++ @placeholder
loading
@endplaceholder ++
ready
++ @assets @endassets ++ @endisland ++
++ HTML; ++ } ++ }); ++ ++ $name = $component->instance()->getIslands()[0]['name']; ++ ++ app('livewire')->update($component->snapshot, [], [ ++ [ ++ 'method' => '__lazyLoadIsland', ++ 'params' => [], ++ 'path' => '', ++ 'metadata' => [ ++ 'island' => ['name' => $name, 'mode' => 'morph'], ++ ], ++ ], ++ ]); ++ ++ $this->assertStringContainsString('/x.js', json_encode(SupportScriptsAndAssets::getAssets())); ++ } ++ ++ public function test_assets_inside_an_explicitly_rendered_island_are_still_shipped() ++ { ++ $component = Livewire::test(new class extends \Livewire\Component { ++ public function refresh() ++ { ++ $this->renderIsland('counter'); ++ } ++ ++ public function render() { ++ return <<<'HTML' ++
++ @island(defer: true, name: 'counter') ++ @placeholder
loading
@endplaceholder ++
ready
++ @assets @endassets ++ @endisland ++
++ HTML; ++ } ++ }); ++ ++ app('livewire')->update($component->snapshot, [], [ ++ [ ++ 'method' => 'refresh', ++ 'params' => [], ++ 'path' => '', ++ ], ++ ]); ++ ++ $this->assertStringContainsString('/y.js', json_encode(SupportScriptsAndAssets::getAssets())); ++ } + } diff --git a/tasks/livewire__livewire-10666/solution/solve.sh b/tasks/livewire__livewire-10666/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/livewire__livewire-10666/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/livewire__livewire-10666/task.toml b/tasks/livewire__livewire-10666/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..853d43c8a329d62d5a74ed25acdb2ebbc0b7dfea --- /dev/null +++ b/tasks/livewire__livewire-10666/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/livewire__livewire-10666" +description = "[4.x] Fix @assets inside implicitly rendered islands not shipping" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "livewire", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "livewire/livewire" +ref = "432402aaced5ce1d7df794e93017f82abb16266f" +reference = "https://github.com/livewire/livewire/pull/10666" +source_access = "auto" +built_at = "2026-11-16T16:09:51.510462+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:0587c05acc4a00d6c67a72b5605af1dc9b70ec2df778f9153e531bf0e8356a8d" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-07T12:08:02Z" +diff_format = "unified" +context_files = [ + "src/Features/SupportIslands/SupportIslands.php", + "src/Features/SupportIslands/UnitTest.php", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 72 +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.406734+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:fc5cb2e2b79ba6e721f2e6c50b1acb53cb34635fac6249e17e0d15f6d040bd20" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/livewire__livewire-10666/tests/capture.py b/tasks/livewire__livewire-10666/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/livewire__livewire-10666/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/livewire__livewire-10666/tests/instruction.md b/tasks/livewire__livewire-10666/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..56a988586ee2f014460da9c0e1671c66d4b17c1a --- /dev/null +++ b/tasks/livewire__livewire-10666/tests/instruction.md @@ -0,0 +1,18 @@ +# Issue + +**Title:** [4.x] Fix @assets inside implicitly rendered islands not shipping + +## Description + +`@assets` inside an implicitly rendered island (deferred, lazy, `skip` + `wire:intersect`, or any `wire:*` action fired from inside an island) stopped shipping after #10529 batched implicit island morphs into `SupportIslands::dehydrate()`. `SupportScriptsAndAssets` is registered earlier in the service provider, so its `dehydrate()` already copies the component's asset store into the response before the island actually renders and pushes its `@assets` block. + +This adds a `before('dehydrate', ...)` hook from `SupportIslands::provide()` that flushes queued implicit island renders ahead of every other feature's `dehydrate()`, regardless of registration order, so the pushed assets are already in the store by the time they're collected. An explicit `$this->renderIsland()` call from an action runs synchronously during the action itself, so it was never affected and stays unaffected. + +Verification: +- Focused SupportIslands unit suite: 27 tests, 54 assertions +- Focused SupportIslands + SupportScriptsAndAssets browser suites: 53 tests +- Full unit suite: 1462 tests + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `432402aaced5`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10666/tests/oracle.patch b/tasks/livewire__livewire-10666/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..bf36869b2f53f108467679fd85da8b9fc54b3cbe --- /dev/null +++ b/tasks/livewire__livewire-10666/tests/oracle.patch @@ -0,0 +1,105 @@ +diff --git a/src/Features/SupportIslands/SupportIslands.php b/src/Features/SupportIslands/SupportIslands.php +index 5c128ddf..d68b6c56 100644 +--- a/src/Features/SupportIslands/SupportIslands.php ++++ b/src/Features/SupportIslands/SupportIslands.php +@@ -6,12 +6,19 @@ use Livewire\Features\SupportIslands\Compiler\IslandCompiler; + use Illuminate\Support\Facades\Blade; + use Livewire\ComponentHook; + ++use function Livewire\before; ++ + class SupportIslands extends ComponentHook + { + public static function provide() + { + static::registerInlineIslandPrecompiler(); + static::registerIslandDirective(); ++ ++ // Flush implicit island renders before any dehydrate hook, so other hooks (e.g. assets) see their output... ++ before('dehydrate', function ($component) { ++ $component->renderImplicitIslandMorphs(); ++ }); + } + + public static function registerIslandDirective() +diff --git a/src/Features/SupportIslands/UnitTest.php b/src/Features/SupportIslands/UnitTest.php +index fe7374a0..8438a0eb 100644 +--- a/src/Features/SupportIslands/UnitTest.php ++++ b/src/Features/SupportIslands/UnitTest.php +@@ -5,6 +5,7 @@ namespace Livewire\Features\SupportIslands; + use Tests\TestCase; + use Livewire\Livewire; + use Livewire\Features\SupportIslands\Compiler\IslandCompiler; ++use Livewire\Features\SupportScriptsAndAssets\SupportScriptsAndAssets; + use Illuminate\Support\Facades\File; + + class UnitTest extends TestCase +@@ -739,4 +740,68 @@ class UnitTest extends TestCase + $this->assertStringNotContainsString('child 1', $component->html()); + $this->assertStringNotContainsString('child 2', $component->html()); + } ++ ++ public function test_assets_inside_an_implicitly_rendered_island_are_shipped() ++ { ++ $component = Livewire::test(new class extends \Livewire\Component { ++ public function render() { ++ return <<<'HTML' ++
++ @island(defer: true) ++ @placeholder
loading
@endplaceholder ++
ready
++ @assets @endassets ++ @endisland ++
++ HTML; ++ } ++ }); ++ ++ $name = $component->instance()->getIslands()[0]['name']; ++ ++ app('livewire')->update($component->snapshot, [], [ ++ [ ++ 'method' => '__lazyLoadIsland', ++ 'params' => [], ++ 'path' => '', ++ 'metadata' => [ ++ 'island' => ['name' => $name, 'mode' => 'morph'], ++ ], ++ ], ++ ]); ++ ++ $this->assertStringContainsString('/x.js', json_encode(SupportScriptsAndAssets::getAssets())); ++ } ++ ++ public function test_assets_inside_an_explicitly_rendered_island_are_still_shipped() ++ { ++ $component = Livewire::test(new class extends \Livewire\Component { ++ public function refresh() ++ { ++ $this->renderIsland('counter'); ++ } ++ ++ public function render() { ++ return <<<'HTML' ++
++ @island(defer: true, name: 'counter') ++ @placeholder
loading
@endplaceholder ++
ready
++ @assets @endassets ++ @endisland ++
++ HTML; ++ } ++ }); ++ ++ app('livewire')->update($component->snapshot, [], [ ++ [ ++ 'method' => 'refresh', ++ 'params' => [], ++ 'path' => '', ++ ], ++ ]); ++ ++ $this->assertStringContainsString('/y.js', json_encode(SupportScriptsAndAssets::getAssets())); ++ } + } diff --git a/tasks/livewire__livewire-10666/tests/test.sh b/tasks/livewire__livewire-10666/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..35d3a64313dc70b599af571dd36eec63c56df89f --- /dev/null +++ b/tasks/livewire__livewire-10666/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 432402aaced5ce1d7df794e93017f82abb16266f > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/livewire__livewire-10666/tests/verifier.py b/tasks/livewire__livewire-10666/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/livewire__livewire-10666/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/livewire__livewire-10670/environment/Dockerfile b/tasks/livewire__livewire-10670/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..5880f0333edd4073c98f740529788335d976ac6d --- /dev/null +++ b/tasks/livewire__livewire-10670/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/livewire/livewire.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/livewire/livewire.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/livewire/livewire.git +WORKDIR /workspace +RUN git fetch --depth 1 origin ed320c5dd32c4c6f612ef33eb13464e41ade63ab 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard ed320c5dd32c4c6f612ef33eb13464e41ade63ab \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base ed320c5dd32c4c6f612ef33eb13464e41ade63ab \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/livewire__livewire-10670/instruction.md b/tasks/livewire__livewire-10670/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..706faf23270c90ce5980912a402d4a491c6b23d3 --- /dev/null +++ b/tasks/livewire__livewire-10670/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** Require Alpine 3.17.2 on 4.x + +## Description + +Prepare 4.x to consume Alpine 3.17.2. + +The package constraints are updated now; the lockfile remains intentionally unchanged until Alpine v3.17.2 is published to npm. After publication, regenerate the lockfile from the real registry and run the JavaScript/build verification before marking ready. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `ed320c5dd32c`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10670/solution/patch.diff b/tasks/livewire__livewire-10670/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..b2270a71971841c88908897735725d75e7fb12df --- /dev/null +++ b/tasks/livewire__livewire-10670/solution/patch.diff @@ -0,0 +1,34 @@ +diff --git a/package.json b/package.json +index 94198299..89ae6989 100644 +--- a/package.json ++++ b/package.json +@@ -17,18 +17,18 @@ + "vitest": "^3.2.4" + }, + "dependencies": { +- "@alpinejs/anchor": "^3.17.1", +- "@alpinejs/collapse": "^3.17.1", +- "@alpinejs/csp": "^3.17.1", +- "@alpinejs/focus": "^3.17.1", +- "@alpinejs/intersect": "^3.17.1", +- "@alpinejs/mask": "^3.17.1", +- "@alpinejs/morph": "^3.17.1", +- "@alpinejs/persist": "^3.17.1", +- "@alpinejs/resize": "^3.17.1", +- "@alpinejs/sort": "^3.17.1", ++ "@alpinejs/anchor": "^3.17.2", ++ "@alpinejs/collapse": "^3.17.2", ++ "@alpinejs/csp": "^3.17.2", ++ "@alpinejs/focus": "^3.17.2", ++ "@alpinejs/intersect": "^3.17.2", ++ "@alpinejs/mask": "^3.17.2", ++ "@alpinejs/morph": "^3.17.2", ++ "@alpinejs/persist": "^3.17.2", ++ "@alpinejs/resize": "^3.17.2", ++ "@alpinejs/sort": "^3.17.2", + "@vue/reactivity": "^3.2.45", +- "alpinejs": "^3.17.1", ++ "alpinejs": "^3.17.2", + "nprogress": "^0.2.0" + } + } diff --git a/tasks/livewire__livewire-10670/solution/solve.sh b/tasks/livewire__livewire-10670/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/livewire__livewire-10670/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/livewire__livewire-10670/task.toml b/tasks/livewire__livewire-10670/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..10120d1cbe6f3de2ece22975533685a9637f7ad4 --- /dev/null +++ b/tasks/livewire__livewire-10670/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/livewire__livewire-10670" +description = "Require Alpine 3.17.2 on 4.x" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "livewire", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "livewire/livewire" +ref = "ed320c5dd32c4c6f612ef33eb13464e41ade63ab" +reference = "https://github.com/livewire/livewire/pull/10670" +source_access = "auto" +built_at = "2026-11-16T16:09:51.507649+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:da46d331817a524dd623a6cadfecef68ae7bb25ae944e63a36d1f75fb5b6fc96" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-07T13:56:44Z" +diff_format = "unified" +context_files = [ + "package.json", +] +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.407238+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:522d932bf5b5f88a196c42e6dcd43cf7465f934ad0b24f8d8268778e178e0e13" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/livewire__livewire-10670/tests/capture.py b/tasks/livewire__livewire-10670/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/livewire__livewire-10670/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/livewire__livewire-10670/tests/instruction.md b/tasks/livewire__livewire-10670/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..706faf23270c90ce5980912a402d4a491c6b23d3 --- /dev/null +++ b/tasks/livewire__livewire-10670/tests/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** Require Alpine 3.17.2 on 4.x + +## Description + +Prepare 4.x to consume Alpine 3.17.2. + +The package constraints are updated now; the lockfile remains intentionally unchanged until Alpine v3.17.2 is published to npm. After publication, regenerate the lockfile from the real registry and run the JavaScript/build verification before marking ready. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `ed320c5dd32c`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10670/tests/oracle.patch b/tasks/livewire__livewire-10670/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..b2270a71971841c88908897735725d75e7fb12df --- /dev/null +++ b/tasks/livewire__livewire-10670/tests/oracle.patch @@ -0,0 +1,34 @@ +diff --git a/package.json b/package.json +index 94198299..89ae6989 100644 +--- a/package.json ++++ b/package.json +@@ -17,18 +17,18 @@ + "vitest": "^3.2.4" + }, + "dependencies": { +- "@alpinejs/anchor": "^3.17.1", +- "@alpinejs/collapse": "^3.17.1", +- "@alpinejs/csp": "^3.17.1", +- "@alpinejs/focus": "^3.17.1", +- "@alpinejs/intersect": "^3.17.1", +- "@alpinejs/mask": "^3.17.1", +- "@alpinejs/morph": "^3.17.1", +- "@alpinejs/persist": "^3.17.1", +- "@alpinejs/resize": "^3.17.1", +- "@alpinejs/sort": "^3.17.1", ++ "@alpinejs/anchor": "^3.17.2", ++ "@alpinejs/collapse": "^3.17.2", ++ "@alpinejs/csp": "^3.17.2", ++ "@alpinejs/focus": "^3.17.2", ++ "@alpinejs/intersect": "^3.17.2", ++ "@alpinejs/mask": "^3.17.2", ++ "@alpinejs/morph": "^3.17.2", ++ "@alpinejs/persist": "^3.17.2", ++ "@alpinejs/resize": "^3.17.2", ++ "@alpinejs/sort": "^3.17.2", + "@vue/reactivity": "^3.2.45", +- "alpinejs": "^3.17.1", ++ "alpinejs": "^3.17.2", + "nprogress": "^0.2.0" + } + } diff --git a/tasks/livewire__livewire-10670/tests/test.sh b/tasks/livewire__livewire-10670/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..967fd8b5e6a779fd0f9576b74dacd478e3dffd0f --- /dev/null +++ b/tasks/livewire__livewire-10670/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace ed320c5dd32c4c6f612ef33eb13464e41ade63ab > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/livewire__livewire-10670/tests/verifier.py b/tasks/livewire__livewire-10670/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/livewire__livewire-10670/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/livewire__livewire-10671/environment/Dockerfile b/tasks/livewire__livewire-10671/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..8580a52fdb5d83b90be55412e932fbac1943ed9d --- /dev/null +++ b/tasks/livewire__livewire-10671/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/livewire/livewire.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/livewire/livewire.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/livewire/livewire.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 585533388481c5dc6e8c420657ceb29bfd86be32 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 585533388481c5dc6e8c420657ceb29bfd86be32 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 585533388481c5dc6e8c420657ceb29bfd86be32 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/livewire__livewire-10671/instruction.md b/tasks/livewire__livewire-10671/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9737dac1fbb99cb46bff86a7faa355b1ab3474e5 --- /dev/null +++ b/tasks/livewire__livewire-10671/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** Require Alpine 3.17.2 on main + +## Description + +Prepare main to consume Alpine 3.17.2. + +The package constraints are updated now; the lockfile remains intentionally unchanged until Alpine v3.17.2 is published to npm. After publication, regenerate the lockfile from the real registry and run the JavaScript/build verification before marking ready. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `585533388481`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10671/solution/patch.diff b/tasks/livewire__livewire-10671/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..b2270a71971841c88908897735725d75e7fb12df --- /dev/null +++ b/tasks/livewire__livewire-10671/solution/patch.diff @@ -0,0 +1,34 @@ +diff --git a/package.json b/package.json +index 94198299..89ae6989 100644 +--- a/package.json ++++ b/package.json +@@ -17,18 +17,18 @@ + "vitest": "^3.2.4" + }, + "dependencies": { +- "@alpinejs/anchor": "^3.17.1", +- "@alpinejs/collapse": "^3.17.1", +- "@alpinejs/csp": "^3.17.1", +- "@alpinejs/focus": "^3.17.1", +- "@alpinejs/intersect": "^3.17.1", +- "@alpinejs/mask": "^3.17.1", +- "@alpinejs/morph": "^3.17.1", +- "@alpinejs/persist": "^3.17.1", +- "@alpinejs/resize": "^3.17.1", +- "@alpinejs/sort": "^3.17.1", ++ "@alpinejs/anchor": "^3.17.2", ++ "@alpinejs/collapse": "^3.17.2", ++ "@alpinejs/csp": "^3.17.2", ++ "@alpinejs/focus": "^3.17.2", ++ "@alpinejs/intersect": "^3.17.2", ++ "@alpinejs/mask": "^3.17.2", ++ "@alpinejs/morph": "^3.17.2", ++ "@alpinejs/persist": "^3.17.2", ++ "@alpinejs/resize": "^3.17.2", ++ "@alpinejs/sort": "^3.17.2", + "@vue/reactivity": "^3.2.45", +- "alpinejs": "^3.17.1", ++ "alpinejs": "^3.17.2", + "nprogress": "^0.2.0" + } + } diff --git a/tasks/livewire__livewire-10671/solution/solve.sh b/tasks/livewire__livewire-10671/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/livewire__livewire-10671/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/livewire__livewire-10671/task.toml b/tasks/livewire__livewire-10671/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..6be01491d0e409956998f7f9f8d996393690a6a4 --- /dev/null +++ b/tasks/livewire__livewire-10671/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/livewire__livewire-10671" +description = "Require Alpine 3.17.2 on main" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "livewire", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "livewire/livewire" +ref = "585533388481c5dc6e8c420657ceb29bfd86be32" +reference = "https://github.com/livewire/livewire/pull/10671" +source_access = "auto" +built_at = "2026-11-16T16:09:51.506347+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:4d48fd5e2d90662c35dd2ea4e4d0fc8289a97f9a2899897a37e9a0587534088b" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-07T13:56:35Z" +diff_format = "unified" +context_files = [ + "package.json", +] +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.407749+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:bc8534deee694937d3255019e235610bbda897329a224b6cff07bbf0a50bcf92" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/livewire__livewire-10671/tests/capture.py b/tasks/livewire__livewire-10671/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/livewire__livewire-10671/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/livewire__livewire-10671/tests/instruction.md b/tasks/livewire__livewire-10671/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9737dac1fbb99cb46bff86a7faa355b1ab3474e5 --- /dev/null +++ b/tasks/livewire__livewire-10671/tests/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** Require Alpine 3.17.2 on main + +## Description + +Prepare main to consume Alpine 3.17.2. + +The package constraints are updated now; the lockfile remains intentionally unchanged until Alpine v3.17.2 is published to npm. After publication, regenerate the lockfile from the real registry and run the JavaScript/build verification before marking ready. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `585533388481`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10671/tests/oracle.patch b/tasks/livewire__livewire-10671/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..b2270a71971841c88908897735725d75e7fb12df --- /dev/null +++ b/tasks/livewire__livewire-10671/tests/oracle.patch @@ -0,0 +1,34 @@ +diff --git a/package.json b/package.json +index 94198299..89ae6989 100644 +--- a/package.json ++++ b/package.json +@@ -17,18 +17,18 @@ + "vitest": "^3.2.4" + }, + "dependencies": { +- "@alpinejs/anchor": "^3.17.1", +- "@alpinejs/collapse": "^3.17.1", +- "@alpinejs/csp": "^3.17.1", +- "@alpinejs/focus": "^3.17.1", +- "@alpinejs/intersect": "^3.17.1", +- "@alpinejs/mask": "^3.17.1", +- "@alpinejs/morph": "^3.17.1", +- "@alpinejs/persist": "^3.17.1", +- "@alpinejs/resize": "^3.17.1", +- "@alpinejs/sort": "^3.17.1", ++ "@alpinejs/anchor": "^3.17.2", ++ "@alpinejs/collapse": "^3.17.2", ++ "@alpinejs/csp": "^3.17.2", ++ "@alpinejs/focus": "^3.17.2", ++ "@alpinejs/intersect": "^3.17.2", ++ "@alpinejs/mask": "^3.17.2", ++ "@alpinejs/morph": "^3.17.2", ++ "@alpinejs/persist": "^3.17.2", ++ "@alpinejs/resize": "^3.17.2", ++ "@alpinejs/sort": "^3.17.2", + "@vue/reactivity": "^3.2.45", +- "alpinejs": "^3.17.1", ++ "alpinejs": "^3.17.2", + "nprogress": "^0.2.0" + } + } diff --git a/tasks/livewire__livewire-10671/tests/test.sh b/tasks/livewire__livewire-10671/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..68b2f1870aa74e5bd5c6817e4817f9e729fc84f5 --- /dev/null +++ b/tasks/livewire__livewire-10671/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 585533388481c5dc6e8c420657ceb29bfd86be32 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/livewire__livewire-10671/tests/verifier.py b/tasks/livewire__livewire-10671/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/livewire__livewire-10671/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/livewire__livewire-10672/environment/Dockerfile b/tasks/livewire__livewire-10672/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b372777f71d831a45d2df1483c737ed196ba863f --- /dev/null +++ b/tasks/livewire__livewire-10672/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/livewire/livewire.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/livewire/livewire.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/livewire/livewire.git +WORKDIR /workspace +RUN git fetch --depth 1 origin b80ff87ab67167aef15db7eab1020f2961a64e2f 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard b80ff87ab67167aef15db7eab1020f2961a64e2f \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base b80ff87ab67167aef15db7eab1020f2961a64e2f \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/livewire__livewire-10672/instruction.md b/tasks/livewire__livewire-10672/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7600f56ba94ae133f406d025fd863410fc8331e8 --- /dev/null +++ b/tasks/livewire__livewire-10672/instruction.md @@ -0,0 +1,23 @@ +# Issue + +**Title:** Backport eligible 4.x fixes to 3.x + +## Description + +Backport the 4.x fixes that apply to the 3.x architecture: + +- #10653 restores persisted elements before teleport callbacks run +- #10664 allows value-based `x-cloak` variants +- #10674 completes the truncated component-hook documentation +- #10675 supports Blade-rendered cloak attribute values + +The new island-assets change remains 4.x/main-only because 3.x has no islands. + +Verification: +- `npm run build` +- Focused navigation browser regressions: 2 passed +- FrontendAssets unit suite: 11 passed + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `b80ff87ab671`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10672/solution/patch.diff b/tasks/livewire__livewire-10672/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..cd462e01881c8daea3147a848156bcaef92d9c82 --- /dev/null +++ b/tasks/livewire__livewire-10672/solution/patch.diff @@ -0,0 +1,202 @@ +diff --git a/docs/component-hooks.md b/docs/component-hooks.md +index b9dc20fd..a7b9c60f 100644 +--- a/docs/component-hooks.md ++++ b/docs/component-hooks.md +@@ -144,4 +144,4 @@ class SupportCsvDownloads extends ComponentHook + } + ``` + +-You can ++The callback returned from `call()` runs after the component method has finished. In this example, it can inspect each method's return value and handle `Csv` instances in one place. +diff --git a/js/plugins/navigate/persist.js b/js/plugins/navigate/persist.js +index edb65809..90c56664 100644 +--- a/js/plugins/navigate/persist.js ++++ b/js/plugins/navigate/persist.js +@@ -18,6 +18,7 @@ export function storePersistantElementsForLater(callback) { + + export function putPersistantElementsBack(callback) { + let usedPersists = [] ++ let putBacks = [] + + document.querySelectorAll('[x-persist]').forEach(i => { + let old = els[i.getAttribute('x-persist')] +@@ -29,13 +30,17 @@ export function putPersistantElementsBack(callback) { + + old._x_wasPersisted = true + +- callback(old, i) +- + Alpine.mutateDom(() => { + i.replaceWith(old) + }) ++ ++ putBacks.push([old, i]) + }) + ++ // Wait until every persisted element is back on the page before running the ++ // callbacks, otherwise a teleport can't resolve a target inside one of them... ++ putBacks.forEach(([old, i]) => callback(old, i)) ++ + Object.entries(els).forEach(([key, el]) => { + if (usedPersists.includes(key)) return + +diff --git a/js/plugins/navigate/teleport.js b/js/plugins/navigate/teleport.js +index 81eabd9f..fbc7f917 100644 +--- a/js/plugins/navigate/teleport.js ++++ b/js/plugins/navigate/teleport.js +@@ -17,7 +17,7 @@ export function removeAnyLeftOverStaleTeleportTargets(body) { + } + + export function unPackPersistedTeleports(persistedEl) { +- // Before we put back any persisted elements, we're going to ++ // Now that the persisted elements are back on the page, we're going to + // find any "x-teleports" and put their targets back on the page... + Alpine.walk(persistedEl, (el, skip) => { + if (! el._x_teleport) return; +diff --git a/src/Features/SupportNavigate/BrowserTest.php b/src/Features/SupportNavigate/BrowserTest.php +index 9cde959a..1610f12d 100644 +--- a/src/Features/SupportNavigate/BrowserTest.php ++++ b/src/Features/SupportNavigate/BrowserTest.php +@@ -243,6 +243,122 @@ class BrowserTest extends \Tests\BrowserTestCase + ; + } + ++ public function test_navigate_works_with_teleports_targeting_inside_a_persist() ++ { ++ $this->registerComponentTestRoutes([ ++ '/second' => new class extends Component { ++ public function render(){ return <<<'HTML' ++
++
++ On second page ++
++ ++ @persist('header') ++
Placeholder
++ @endpersist ++
++ HTML; } ++ }, ++ ]); ++ ++ Livewire::visit(new class extends Component { ++ public function render(){ ++ return <<<'HTML' ++
++
++ On first page ++
++ ++ @persist('header') ++
++
++ ++ ++
++ @endpersist ++ ++ Go to second page ++
++ HTML; ++ } ++ }) ++ ->assertSeeIn('@target', '0') ++ ->click('@button') ++ ->assertSeeIn('@target', '1') ++ ->click('@link') ++ ->waitForText('On second page') ++ ->assertSeeIn('@target', '1') ++ ->click('@button') ++ ->assertSeeIn('@target', '2') ++ ; ++ } ++ ++ public function test_navigate_works_with_teleports_targeting_inside_another_persist() ++ { ++ $this->registerComponentTestRoutes([ ++ '/second' => new class extends Component { ++ public function render(){ return <<<'HTML' ++
++
++ On second page ++
++ ++ @persist('header') ++
Placeholder
++ @endpersist ++ ++ @persist('sidebar') ++
Placeholder
++ @endpersist ++
++ HTML; } ++ }, ++ ]); ++ ++ Livewire::visit(new class extends Component { ++ public function render(){ ++ return <<<'HTML' ++
++
++ On first page ++
++ ++ @persist('header') ++
++ ++
++ @endpersist ++ ++ @persist('sidebar') ++
++ @endpersist ++ ++ Go to second page ++
++ HTML; ++ } ++ }) ++ ->assertSeeIn('@target', '0') ++ ->click('@button') ++ ->assertSeeIn('@target', '1') ++ ->click('@link') ++ ->waitForText('On second page') ++ ->assertSeeIn('@target', '1') ++ ->click('@button') ++ ->assertSeeIn('@target', '2') ++ ; ++ } ++ + public function test_can_configure_progress_bar() + { + $this->browse(function ($browser) { +diff --git a/src/Mechanisms/FrontendAssets/FrontendAssets.php b/src/Mechanisms/FrontendAssets/FrontendAssets.php +index 1c4d2981..c64172c4 100644 +--- a/src/Mechanisms/FrontendAssets/FrontendAssets.php ++++ b/src/Mechanisms/FrontendAssets/FrontendAssets.php +@@ -127,11 +127,13 @@ class FrontendAssets extends Mechanism + --livewire-progress-bar-color: {$progressBarColor}; + } + +- [x-cloak] { ++ [x-cloak="x-cloak"], ++ [x-cloak=""] { + display: none !important; + } + +- [wire\:cloak] { ++ [wire\:cloak="wire:cloak"], ++ [wire\:cloak=""] { + display: none !important; + } + diff --git a/tasks/livewire__livewire-10672/solution/solve.sh b/tasks/livewire__livewire-10672/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/livewire__livewire-10672/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/livewire__livewire-10672/task.toml b/tasks/livewire__livewire-10672/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..fa6aafa488b6f72116d3413be6ed37eabf51a521 --- /dev/null +++ b/tasks/livewire__livewire-10672/task.toml @@ -0,0 +1,72 @@ +version = "1.0" + +[task] +name = "trending/livewire__livewire-10672" +description = "Backport eligible 4.x fixes to 3.x" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "livewire", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "livewire/livewire" +ref = "b80ff87ab67167aef15db7eab1020f2961a64e2f" +reference = "https://github.com/livewire/livewire/pull/10672" +source_access = "auto" +built_at = "2026-11-16T16:09:51.504975+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:af2634d4eea7b890e8fe9db3ddb1c21b80d3d7b84db30d65bf3bfa18244719a9" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-07T13:57:17Z" +diff_format = "unified" +context_files = [ + "docs/component-hooks.md", + "js/plugins/navigate/persist.js", + "js/plugins/navigate/teleport.js", + "src/Features/SupportNavigate/BrowserTest.php", + "src/Mechanisms/FrontendAssets/FrontendAssets.php", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 135 +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.408252+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:970357be46bfea496fd0faca98d5c43ce16d578c42f33b3ba98bf602c38618b2" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/livewire__livewire-10672/tests/capture.py b/tasks/livewire__livewire-10672/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/livewire__livewire-10672/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/livewire__livewire-10672/tests/instruction.md b/tasks/livewire__livewire-10672/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7600f56ba94ae133f406d025fd863410fc8331e8 --- /dev/null +++ b/tasks/livewire__livewire-10672/tests/instruction.md @@ -0,0 +1,23 @@ +# Issue + +**Title:** Backport eligible 4.x fixes to 3.x + +## Description + +Backport the 4.x fixes that apply to the 3.x architecture: + +- #10653 restores persisted elements before teleport callbacks run +- #10664 allows value-based `x-cloak` variants +- #10674 completes the truncated component-hook documentation +- #10675 supports Blade-rendered cloak attribute values + +The new island-assets change remains 4.x/main-only because 3.x has no islands. + +Verification: +- `npm run build` +- Focused navigation browser regressions: 2 passed +- FrontendAssets unit suite: 11 passed + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `b80ff87ab671`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10672/tests/oracle.patch b/tasks/livewire__livewire-10672/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..cd462e01881c8daea3147a848156bcaef92d9c82 --- /dev/null +++ b/tasks/livewire__livewire-10672/tests/oracle.patch @@ -0,0 +1,202 @@ +diff --git a/docs/component-hooks.md b/docs/component-hooks.md +index b9dc20fd..a7b9c60f 100644 +--- a/docs/component-hooks.md ++++ b/docs/component-hooks.md +@@ -144,4 +144,4 @@ class SupportCsvDownloads extends ComponentHook + } + ``` + +-You can ++The callback returned from `call()` runs after the component method has finished. In this example, it can inspect each method's return value and handle `Csv` instances in one place. +diff --git a/js/plugins/navigate/persist.js b/js/plugins/navigate/persist.js +index edb65809..90c56664 100644 +--- a/js/plugins/navigate/persist.js ++++ b/js/plugins/navigate/persist.js +@@ -18,6 +18,7 @@ export function storePersistantElementsForLater(callback) { + + export function putPersistantElementsBack(callback) { + let usedPersists = [] ++ let putBacks = [] + + document.querySelectorAll('[x-persist]').forEach(i => { + let old = els[i.getAttribute('x-persist')] +@@ -29,13 +30,17 @@ export function putPersistantElementsBack(callback) { + + old._x_wasPersisted = true + +- callback(old, i) +- + Alpine.mutateDom(() => { + i.replaceWith(old) + }) ++ ++ putBacks.push([old, i]) + }) + ++ // Wait until every persisted element is back on the page before running the ++ // callbacks, otherwise a teleport can't resolve a target inside one of them... ++ putBacks.forEach(([old, i]) => callback(old, i)) ++ + Object.entries(els).forEach(([key, el]) => { + if (usedPersists.includes(key)) return + +diff --git a/js/plugins/navigate/teleport.js b/js/plugins/navigate/teleport.js +index 81eabd9f..fbc7f917 100644 +--- a/js/plugins/navigate/teleport.js ++++ b/js/plugins/navigate/teleport.js +@@ -17,7 +17,7 @@ export function removeAnyLeftOverStaleTeleportTargets(body) { + } + + export function unPackPersistedTeleports(persistedEl) { +- // Before we put back any persisted elements, we're going to ++ // Now that the persisted elements are back on the page, we're going to + // find any "x-teleports" and put their targets back on the page... + Alpine.walk(persistedEl, (el, skip) => { + if (! el._x_teleport) return; +diff --git a/src/Features/SupportNavigate/BrowserTest.php b/src/Features/SupportNavigate/BrowserTest.php +index 9cde959a..1610f12d 100644 +--- a/src/Features/SupportNavigate/BrowserTest.php ++++ b/src/Features/SupportNavigate/BrowserTest.php +@@ -243,6 +243,122 @@ class BrowserTest extends \Tests\BrowserTestCase + ; + } + ++ public function test_navigate_works_with_teleports_targeting_inside_a_persist() ++ { ++ $this->registerComponentTestRoutes([ ++ '/second' => new class extends Component { ++ public function render(){ return <<<'HTML' ++
++
++ On second page ++
++ ++ @persist('header') ++
Placeholder
++ @endpersist ++
++ HTML; } ++ }, ++ ]); ++ ++ Livewire::visit(new class extends Component { ++ public function render(){ ++ return <<<'HTML' ++
++
++ On first page ++
++ ++ @persist('header') ++
++
++ ++ ++
++ @endpersist ++ ++ Go to second page ++
++ HTML; ++ } ++ }) ++ ->assertSeeIn('@target', '0') ++ ->click('@button') ++ ->assertSeeIn('@target', '1') ++ ->click('@link') ++ ->waitForText('On second page') ++ ->assertSeeIn('@target', '1') ++ ->click('@button') ++ ->assertSeeIn('@target', '2') ++ ; ++ } ++ ++ public function test_navigate_works_with_teleports_targeting_inside_another_persist() ++ { ++ $this->registerComponentTestRoutes([ ++ '/second' => new class extends Component { ++ public function render(){ return <<<'HTML' ++
++
++ On second page ++
++ ++ @persist('header') ++
Placeholder
++ @endpersist ++ ++ @persist('sidebar') ++
Placeholder
++ @endpersist ++
++ HTML; } ++ }, ++ ]); ++ ++ Livewire::visit(new class extends Component { ++ public function render(){ ++ return <<<'HTML' ++
++
++ On first page ++
++ ++ @persist('header') ++
++ ++
++ @endpersist ++ ++ @persist('sidebar') ++
++ @endpersist ++ ++ Go to second page ++
++ HTML; ++ } ++ }) ++ ->assertSeeIn('@target', '0') ++ ->click('@button') ++ ->assertSeeIn('@target', '1') ++ ->click('@link') ++ ->waitForText('On second page') ++ ->assertSeeIn('@target', '1') ++ ->click('@button') ++ ->assertSeeIn('@target', '2') ++ ; ++ } ++ + public function test_can_configure_progress_bar() + { + $this->browse(function ($browser) { +diff --git a/src/Mechanisms/FrontendAssets/FrontendAssets.php b/src/Mechanisms/FrontendAssets/FrontendAssets.php +index 1c4d2981..c64172c4 100644 +--- a/src/Mechanisms/FrontendAssets/FrontendAssets.php ++++ b/src/Mechanisms/FrontendAssets/FrontendAssets.php +@@ -127,11 +127,13 @@ class FrontendAssets extends Mechanism + --livewire-progress-bar-color: {$progressBarColor}; + } + +- [x-cloak] { ++ [x-cloak="x-cloak"], ++ [x-cloak=""] { + display: none !important; + } + +- [wire\:cloak] { ++ [wire\:cloak="wire:cloak"], ++ [wire\:cloak=""] { + display: none !important; + } + diff --git a/tasks/livewire__livewire-10672/tests/test.sh b/tasks/livewire__livewire-10672/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..d7000cd2dcb2d9933ce893abb30bda7eee6ef46b --- /dev/null +++ b/tasks/livewire__livewire-10672/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace b80ff87ab67167aef15db7eab1020f2961a64e2f > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/livewire__livewire-10672/tests/verifier.py b/tasks/livewire__livewire-10672/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/livewire__livewire-10672/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/livewire__livewire-10676/environment/Dockerfile b/tasks/livewire__livewire-10676/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..f6443e7066390185dabb92c66336009e849ad950 --- /dev/null +++ b/tasks/livewire__livewire-10676/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/livewire/livewire.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/livewire/livewire.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/livewire/livewire.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 3da3c48c7c98672af7289646b1e65288aed83ebb 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 3da3c48c7c98672af7289646b1e65288aed83ebb \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 3da3c48c7c98672af7289646b1e65288aed83ebb \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/livewire__livewire-10676/instruction.md b/tasks/livewire__livewire-10676/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c592c6f13e7957b8f09892056cf266b8045823f7 --- /dev/null +++ b/tasks/livewire__livewire-10676/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** Update Alpine 3.17.2 lockfile on 4.x + +## Description + +Updates `package-lock.json` to match the Alpine 3.17.2 constraints already merged in #10670. + +This fixes the exact-head `npm ci` failure on 4.x. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `3da3c48c7c98`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10676/solution/patch.diff b/tasks/livewire__livewire-10676/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..b7ca5539d3d424f208514f714013bc11378d1be6 --- /dev/null +++ b/tasks/livewire__livewire-10676/solution/patch.diff @@ -0,0 +1,151 @@ +diff --git a/package-lock.json b/package-lock.json +index 9dcd46c9..2f324395 100644 +--- a/package-lock.json ++++ b/package-lock.json +@@ -7,18 +7,18 @@ + "name": "laravel-livewire", + "license": "MIT", + "dependencies": { +- "@alpinejs/anchor": "^3.17.1", +- "@alpinejs/collapse": "^3.17.1", +- "@alpinejs/csp": "^3.17.1", +- "@alpinejs/focus": "^3.17.1", +- "@alpinejs/intersect": "^3.17.1", +- "@alpinejs/mask": "^3.17.1", +- "@alpinejs/morph": "^3.17.1", +- "@alpinejs/persist": "^3.17.1", +- "@alpinejs/resize": "^3.17.1", +- "@alpinejs/sort": "^3.17.1", ++ "@alpinejs/anchor": "^3.17.2", ++ "@alpinejs/collapse": "^3.17.2", ++ "@alpinejs/csp": "^3.17.2", ++ "@alpinejs/focus": "^3.17.2", ++ "@alpinejs/intersect": "^3.17.2", ++ "@alpinejs/mask": "^3.17.2", ++ "@alpinejs/morph": "^3.17.2", ++ "@alpinejs/persist": "^3.17.2", ++ "@alpinejs/resize": "^3.17.2", ++ "@alpinejs/sort": "^3.17.2", + "@vue/reactivity": "^3.2.45", +- "alpinejs": "^3.17.1", ++ "alpinejs": "^3.17.2", + "nprogress": "^0.2.0" + }, + "devDependencies": { +@@ -29,33 +29,33 @@ + } + }, + "node_modules/@alpinejs/anchor": { +- "version": "3.17.1", +- "resolved": "https://registry.npmjs.org/@alpinejs/anchor/-/anchor-3.17.1.tgz", +- "integrity": "sha512-x6mVH3CAUKLMMh1jEgJ7pWi9DzKEgTq6pK391wN1MvSLndjr0RYOyfCakS1Y6SqHZbTyRtwfp3zG3ECoFYILKw==", ++ "version": "3.17.2", ++ "resolved": "https://registry.npmjs.org/@alpinejs/anchor/-/anchor-3.17.2.tgz", ++ "integrity": "sha512-b4I/HwzG6o1L1hOcuGSxDuFUVJH4MgKWC+xr5fxWvUNeqqsTyB0ioqhfcqoA0vvIFnm9eLhGuwiKt4FymZis0A==", + "license": "MIT", + "dependencies": { + "@floating-ui/dom": "^1.5.3" + } + }, + "node_modules/@alpinejs/collapse": { +- "version": "3.17.1", +- "resolved": "https://registry.npmjs.org/@alpinejs/collapse/-/collapse-3.17.1.tgz", +- "integrity": "sha512-ygf0kJ2I+1TgBUjS+V1Dx2KlT/y/AatyfavzL7b2T3qrPx7WRGI4yxvFB0h6J5OZVO08dhtDTVk/Z1GIC6ME/w==", ++ "version": "3.17.2", ++ "resolved": "https://registry.npmjs.org/@alpinejs/collapse/-/collapse-3.17.2.tgz", ++ "integrity": "sha512-OugjrAUGXkg8Msmitgf3rXFyoSYXchN00LPQYC2zDjaTcuRaVXXseBZcCU7DZ7b6cyZzCvYbIYngbaaEzvEfuw==", + "license": "MIT" + }, + "node_modules/@alpinejs/csp": { +- "version": "3.17.1", +- "resolved": "https://registry.npmjs.org/@alpinejs/csp/-/csp-3.17.1.tgz", +- "integrity": "sha512-HDrY0ZxvJWSmeUYqtHVSsitaqy1es3VDCNodPpdQRX4nHhHiRoeib+rOzRFFStFRD/6x0KmQzJVJ4FCLAI/DUQ==", ++ "version": "3.17.2", ++ "resolved": "https://registry.npmjs.org/@alpinejs/csp/-/csp-3.17.2.tgz", ++ "integrity": "sha512-jJXIzBaplTu1xVuhtNXEYDQDbQrdVJbXHYSVeF22fz4Vzm+g0X2XMb4pY1ywEpYLsFRx7ZcBE5gMyyuJpKPfHg==", + "license": "MIT", + "dependencies": { + "@vue/reactivity": "~3.5.40" + } + }, + "node_modules/@alpinejs/focus": { +- "version": "3.17.1", +- "resolved": "https://registry.npmjs.org/@alpinejs/focus/-/focus-3.17.1.tgz", +- "integrity": "sha512-23+9xUfPMhuqIm6xeqLQmQTBjNY/yHtJ5np05WrFZLdKXOXCLktpAE7ZAgmPoD/s7F2banEiJzTSFDO6GnWUIg==", ++ "version": "3.17.2", ++ "resolved": "https://registry.npmjs.org/@alpinejs/focus/-/focus-3.17.2.tgz", ++ "integrity": "sha512-ZYER+iuYu9IHT2ihAaP04alQLzLzH5nEMmFwVDe7Yu6bzeub+yJISYjR2hH+DlQTcmAZc7xnFMb6zscCVI091Q==", + "license": "MIT", + "dependencies": { + "focus-trap": "^8.0.0", +@@ -63,39 +63,39 @@ + } + }, + "node_modules/@alpinejs/intersect": { +- "version": "3.17.1", +- "resolved": "https://registry.npmjs.org/@alpinejs/intersect/-/intersect-3.17.1.tgz", +- "integrity": "sha512-60UZyk6BNGocHgEvKxBfgqPXq9Y1tuQ363/FjdlXc1eNI8Q0arelStWLhEyd0u8JJp7FTr50S/CmaYXMijTQYQ==", ++ "version": "3.17.2", ++ "resolved": "https://registry.npmjs.org/@alpinejs/intersect/-/intersect-3.17.2.tgz", ++ "integrity": "sha512-q4AJZDk7l/q7PaLeacMmdCfCCtgU3Qve9QTt4t6+A0z8F3YU2xqku08O9N7IENwiPKxlWseqXWWSlr97FSyZ9w==", + "license": "MIT" + }, + "node_modules/@alpinejs/mask": { +- "version": "3.17.1", +- "resolved": "https://registry.npmjs.org/@alpinejs/mask/-/mask-3.17.1.tgz", +- "integrity": "sha512-EK/6nkVdO0kyLM/xYag6oJ2jEbQevEfsdRdjUnwJnzCcLLulUpTLo0JVRBml9XBobM614pVOEMzdbXPPI0wB9w==", ++ "version": "3.17.2", ++ "resolved": "https://registry.npmjs.org/@alpinejs/mask/-/mask-3.17.2.tgz", ++ "integrity": "sha512-o2ht803nXshsYyNFvR4cUg/9XijF9eqwN8FFEVJUxriVJRS5jWDVADjijHcjQuVKGJYmzdnUMSLBPv48F8In9Q==", + "license": "MIT" + }, + "node_modules/@alpinejs/morph": { +- "version": "3.17.1", +- "resolved": "https://registry.npmjs.org/@alpinejs/morph/-/morph-3.17.1.tgz", +- "integrity": "sha512-RVafJn9fsF1mrxbQniSgTyneV4ybEFPgBGsjwpxko1g0WPdctTewgnxxO86gy5VztpjNvpjRW1bcpq39WtMt8w==", ++ "version": "3.17.2", ++ "resolved": "https://registry.npmjs.org/@alpinejs/morph/-/morph-3.17.2.tgz", ++ "integrity": "sha512-9O+m1ChwU3JNFsTY7WDAOdG3qPYmE5zJp+2XWX/ymc57S9ifmmx0RCnRR/14CPEqTc/cdpUIOlnAGBg0NAGHpw==", + "license": "MIT" + }, + "node_modules/@alpinejs/persist": { +- "version": "3.17.1", +- "resolved": "https://registry.npmjs.org/@alpinejs/persist/-/persist-3.17.1.tgz", +- "integrity": "sha512-PN/93FIWakZYY4zB/VGDlFtx2LOoa318huflgLMo2jsk+pkjLlDkX1qmuUFh5xhI7Uj3vSvU1Eu1WIA3TN3PTA==", ++ "version": "3.17.2", ++ "resolved": "https://registry.npmjs.org/@alpinejs/persist/-/persist-3.17.2.tgz", ++ "integrity": "sha512-BN8v27efELn2IgWjFoY0IkUmT1JOt3gUwEIb+2rjCU875E6VDbc6n0d29l9giITRgqyugm00H/xB1kcPVrQlcQ==", + "license": "MIT" + }, + "node_modules/@alpinejs/resize": { +- "version": "3.17.1", +- "resolved": "https://registry.npmjs.org/@alpinejs/resize/-/resize-3.17.1.tgz", +- "integrity": "sha512-TyHYMY6DQBh9P/hOFH3KGLE7ilyfR3u3qsYtJfpsE6Fq8eKobkjudahmhHmdiGurohx8YaVbWBNilDcnAjLOTw==", ++ "version": "3.17.2", ++ "resolved": "https://registry.npmjs.org/@alpinejs/resize/-/resize-3.17.2.tgz", ++ "integrity": "sha512-6v/LECG5pHMh/5iAY/PSPilZZtgt6kVmbpTTyLScmusIt1wyGqbX/wLXJnJwnr40Swb3B4ZImEBK9r1+GDlC8g==", + "license": "MIT" + }, + "node_modules/@alpinejs/sort": { +- "version": "3.17.1", +- "resolved": "https://registry.npmjs.org/@alpinejs/sort/-/sort-3.17.1.tgz", +- "integrity": "sha512-Q6qF00WI4cQAZdIxPgbsHnxZIiIv4T1kfSPyEy2QB/SLhLdISuIjzTBa3TQAe1P45BkRtNk5Y8fQuDZuKhN/6w==", ++ "version": "3.17.2", ++ "resolved": "https://registry.npmjs.org/@alpinejs/sort/-/sort-3.17.2.tgz", ++ "integrity": "sha512-72v63zuFkepgO2nwi8wNrD1z6pAY3S+d+lCwSZ9Q39hkIFISxPXKffEh3qtTu7Dzlc98EYLz4kVS/pxp3mdw5g==", + "license": "MIT", + "dependencies": { + "sortablejs": "^1.15.2" +@@ -1266,9 +1266,9 @@ + } + }, + "node_modules/alpinejs": { +- "version": "3.17.1", +- "resolved": "https://registry.npmjs.org/alpinejs/-/alpinejs-3.17.1.tgz", +- "integrity": "sha512-HDUhA9juSA/pNYZ5FAAlW4qNsdeVORFSVONEIu0hVasqCOqLitf15R9tCr5GBCV0ZxiZW2Qx6BYdMSF7iGLT/Q==", ++ "version": "3.17.2", ++ "resolved": "https://registry.npmjs.org/alpinejs/-/alpinejs-3.17.2.tgz", ++ "integrity": "sha512-xbnG3LlnmFkiNO49C+qhqjEDqOdB0snKqvT48ZVp8TakpZOpsoQbc/jAxpptQRjZi7c9rLeCfvwQ/XOSirIZFQ==", + "license": "MIT", + "dependencies": { + "@vue/reactivity": "~3.5.40" diff --git a/tasks/livewire__livewire-10676/solution/solve.sh b/tasks/livewire__livewire-10676/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/livewire__livewire-10676/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/livewire__livewire-10676/task.toml b/tasks/livewire__livewire-10676/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..0bd57b440ebbab84c5d66d3483edfbdf642481fb --- /dev/null +++ b/tasks/livewire__livewire-10676/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/livewire__livewire-10676" +description = "Update Alpine 3.17.2 lockfile on 4.x" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "livewire", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "livewire/livewire" +ref = "3da3c48c7c98672af7289646b1e65288aed83ebb" +reference = "https://github.com/livewire/livewire/pull/10676" +source_access = "auto" +built_at = "2026-11-16T16:09:51.503558+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:f0e8f602c56ffebafe4b4a000997092568e2b3b398caf898e3a13677d45eb788" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-07T15:32:46Z" +diff_format = "unified" +context_files = [ + "package-lock.json", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 88 +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.408793+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:131f18b0dfd0a724ed53ccc0ef719f3c22a63f5c0ba3afec000d046eac0d1c7b" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/livewire__livewire-10676/tests/capture.py b/tasks/livewire__livewire-10676/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/livewire__livewire-10676/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/livewire__livewire-10676/tests/instruction.md b/tasks/livewire__livewire-10676/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c592c6f13e7957b8f09892056cf266b8045823f7 --- /dev/null +++ b/tasks/livewire__livewire-10676/tests/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** Update Alpine 3.17.2 lockfile on 4.x + +## Description + +Updates `package-lock.json` to match the Alpine 3.17.2 constraints already merged in #10670. + +This fixes the exact-head `npm ci` failure on 4.x. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `3da3c48c7c98`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10676/tests/oracle.patch b/tasks/livewire__livewire-10676/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..b7ca5539d3d424f208514f714013bc11378d1be6 --- /dev/null +++ b/tasks/livewire__livewire-10676/tests/oracle.patch @@ -0,0 +1,151 @@ +diff --git a/package-lock.json b/package-lock.json +index 9dcd46c9..2f324395 100644 +--- a/package-lock.json ++++ b/package-lock.json +@@ -7,18 +7,18 @@ + "name": "laravel-livewire", + "license": "MIT", + "dependencies": { +- "@alpinejs/anchor": "^3.17.1", +- "@alpinejs/collapse": "^3.17.1", +- "@alpinejs/csp": "^3.17.1", +- "@alpinejs/focus": "^3.17.1", +- "@alpinejs/intersect": "^3.17.1", +- "@alpinejs/mask": "^3.17.1", +- "@alpinejs/morph": "^3.17.1", +- "@alpinejs/persist": "^3.17.1", +- "@alpinejs/resize": "^3.17.1", +- "@alpinejs/sort": "^3.17.1", ++ "@alpinejs/anchor": "^3.17.2", ++ "@alpinejs/collapse": "^3.17.2", ++ "@alpinejs/csp": "^3.17.2", ++ "@alpinejs/focus": "^3.17.2", ++ "@alpinejs/intersect": "^3.17.2", ++ "@alpinejs/mask": "^3.17.2", ++ "@alpinejs/morph": "^3.17.2", ++ "@alpinejs/persist": "^3.17.2", ++ "@alpinejs/resize": "^3.17.2", ++ "@alpinejs/sort": "^3.17.2", + "@vue/reactivity": "^3.2.45", +- "alpinejs": "^3.17.1", ++ "alpinejs": "^3.17.2", + "nprogress": "^0.2.0" + }, + "devDependencies": { +@@ -29,33 +29,33 @@ + } + }, + "node_modules/@alpinejs/anchor": { +- "version": "3.17.1", +- "resolved": "https://registry.npmjs.org/@alpinejs/anchor/-/anchor-3.17.1.tgz", +- "integrity": "sha512-x6mVH3CAUKLMMh1jEgJ7pWi9DzKEgTq6pK391wN1MvSLndjr0RYOyfCakS1Y6SqHZbTyRtwfp3zG3ECoFYILKw==", ++ "version": "3.17.2", ++ "resolved": "https://registry.npmjs.org/@alpinejs/anchor/-/anchor-3.17.2.tgz", ++ "integrity": "sha512-b4I/HwzG6o1L1hOcuGSxDuFUVJH4MgKWC+xr5fxWvUNeqqsTyB0ioqhfcqoA0vvIFnm9eLhGuwiKt4FymZis0A==", + "license": "MIT", + "dependencies": { + "@floating-ui/dom": "^1.5.3" + } + }, + "node_modules/@alpinejs/collapse": { +- "version": "3.17.1", +- "resolved": "https://registry.npmjs.org/@alpinejs/collapse/-/collapse-3.17.1.tgz", +- "integrity": "sha512-ygf0kJ2I+1TgBUjS+V1Dx2KlT/y/AatyfavzL7b2T3qrPx7WRGI4yxvFB0h6J5OZVO08dhtDTVk/Z1GIC6ME/w==", ++ "version": "3.17.2", ++ "resolved": "https://registry.npmjs.org/@alpinejs/collapse/-/collapse-3.17.2.tgz", ++ "integrity": "sha512-OugjrAUGXkg8Msmitgf3rXFyoSYXchN00LPQYC2zDjaTcuRaVXXseBZcCU7DZ7b6cyZzCvYbIYngbaaEzvEfuw==", + "license": "MIT" + }, + "node_modules/@alpinejs/csp": { +- "version": "3.17.1", +- "resolved": "https://registry.npmjs.org/@alpinejs/csp/-/csp-3.17.1.tgz", +- "integrity": "sha512-HDrY0ZxvJWSmeUYqtHVSsitaqy1es3VDCNodPpdQRX4nHhHiRoeib+rOzRFFStFRD/6x0KmQzJVJ4FCLAI/DUQ==", ++ "version": "3.17.2", ++ "resolved": "https://registry.npmjs.org/@alpinejs/csp/-/csp-3.17.2.tgz", ++ "integrity": "sha512-jJXIzBaplTu1xVuhtNXEYDQDbQrdVJbXHYSVeF22fz4Vzm+g0X2XMb4pY1ywEpYLsFRx7ZcBE5gMyyuJpKPfHg==", + "license": "MIT", + "dependencies": { + "@vue/reactivity": "~3.5.40" + } + }, + "node_modules/@alpinejs/focus": { +- "version": "3.17.1", +- "resolved": "https://registry.npmjs.org/@alpinejs/focus/-/focus-3.17.1.tgz", +- "integrity": "sha512-23+9xUfPMhuqIm6xeqLQmQTBjNY/yHtJ5np05WrFZLdKXOXCLktpAE7ZAgmPoD/s7F2banEiJzTSFDO6GnWUIg==", ++ "version": "3.17.2", ++ "resolved": "https://registry.npmjs.org/@alpinejs/focus/-/focus-3.17.2.tgz", ++ "integrity": "sha512-ZYER+iuYu9IHT2ihAaP04alQLzLzH5nEMmFwVDe7Yu6bzeub+yJISYjR2hH+DlQTcmAZc7xnFMb6zscCVI091Q==", + "license": "MIT", + "dependencies": { + "focus-trap": "^8.0.0", +@@ -63,39 +63,39 @@ + } + }, + "node_modules/@alpinejs/intersect": { +- "version": "3.17.1", +- "resolved": "https://registry.npmjs.org/@alpinejs/intersect/-/intersect-3.17.1.tgz", +- "integrity": "sha512-60UZyk6BNGocHgEvKxBfgqPXq9Y1tuQ363/FjdlXc1eNI8Q0arelStWLhEyd0u8JJp7FTr50S/CmaYXMijTQYQ==", ++ "version": "3.17.2", ++ "resolved": "https://registry.npmjs.org/@alpinejs/intersect/-/intersect-3.17.2.tgz", ++ "integrity": "sha512-q4AJZDk7l/q7PaLeacMmdCfCCtgU3Qve9QTt4t6+A0z8F3YU2xqku08O9N7IENwiPKxlWseqXWWSlr97FSyZ9w==", + "license": "MIT" + }, + "node_modules/@alpinejs/mask": { +- "version": "3.17.1", +- "resolved": "https://registry.npmjs.org/@alpinejs/mask/-/mask-3.17.1.tgz", +- "integrity": "sha512-EK/6nkVdO0kyLM/xYag6oJ2jEbQevEfsdRdjUnwJnzCcLLulUpTLo0JVRBml9XBobM614pVOEMzdbXPPI0wB9w==", ++ "version": "3.17.2", ++ "resolved": "https://registry.npmjs.org/@alpinejs/mask/-/mask-3.17.2.tgz", ++ "integrity": "sha512-o2ht803nXshsYyNFvR4cUg/9XijF9eqwN8FFEVJUxriVJRS5jWDVADjijHcjQuVKGJYmzdnUMSLBPv48F8In9Q==", + "license": "MIT" + }, + "node_modules/@alpinejs/morph": { +- "version": "3.17.1", +- "resolved": "https://registry.npmjs.org/@alpinejs/morph/-/morph-3.17.1.tgz", +- "integrity": "sha512-RVafJn9fsF1mrxbQniSgTyneV4ybEFPgBGsjwpxko1g0WPdctTewgnxxO86gy5VztpjNvpjRW1bcpq39WtMt8w==", ++ "version": "3.17.2", ++ "resolved": "https://registry.npmjs.org/@alpinejs/morph/-/morph-3.17.2.tgz", ++ "integrity": "sha512-9O+m1ChwU3JNFsTY7WDAOdG3qPYmE5zJp+2XWX/ymc57S9ifmmx0RCnRR/14CPEqTc/cdpUIOlnAGBg0NAGHpw==", + "license": "MIT" + }, + "node_modules/@alpinejs/persist": { +- "version": "3.17.1", +- "resolved": "https://registry.npmjs.org/@alpinejs/persist/-/persist-3.17.1.tgz", +- "integrity": "sha512-PN/93FIWakZYY4zB/VGDlFtx2LOoa318huflgLMo2jsk+pkjLlDkX1qmuUFh5xhI7Uj3vSvU1Eu1WIA3TN3PTA==", ++ "version": "3.17.2", ++ "resolved": "https://registry.npmjs.org/@alpinejs/persist/-/persist-3.17.2.tgz", ++ "integrity": "sha512-BN8v27efELn2IgWjFoY0IkUmT1JOt3gUwEIb+2rjCU875E6VDbc6n0d29l9giITRgqyugm00H/xB1kcPVrQlcQ==", + "license": "MIT" + }, + "node_modules/@alpinejs/resize": { +- "version": "3.17.1", +- "resolved": "https://registry.npmjs.org/@alpinejs/resize/-/resize-3.17.1.tgz", +- "integrity": "sha512-TyHYMY6DQBh9P/hOFH3KGLE7ilyfR3u3qsYtJfpsE6Fq8eKobkjudahmhHmdiGurohx8YaVbWBNilDcnAjLOTw==", ++ "version": "3.17.2", ++ "resolved": "https://registry.npmjs.org/@alpinejs/resize/-/resize-3.17.2.tgz", ++ "integrity": "sha512-6v/LECG5pHMh/5iAY/PSPilZZtgt6kVmbpTTyLScmusIt1wyGqbX/wLXJnJwnr40Swb3B4ZImEBK9r1+GDlC8g==", + "license": "MIT" + }, + "node_modules/@alpinejs/sort": { +- "version": "3.17.1", +- "resolved": "https://registry.npmjs.org/@alpinejs/sort/-/sort-3.17.1.tgz", +- "integrity": "sha512-Q6qF00WI4cQAZdIxPgbsHnxZIiIv4T1kfSPyEy2QB/SLhLdISuIjzTBa3TQAe1P45BkRtNk5Y8fQuDZuKhN/6w==", ++ "version": "3.17.2", ++ "resolved": "https://registry.npmjs.org/@alpinejs/sort/-/sort-3.17.2.tgz", ++ "integrity": "sha512-72v63zuFkepgO2nwi8wNrD1z6pAY3S+d+lCwSZ9Q39hkIFISxPXKffEh3qtTu7Dzlc98EYLz4kVS/pxp3mdw5g==", + "license": "MIT", + "dependencies": { + "sortablejs": "^1.15.2" +@@ -1266,9 +1266,9 @@ + } + }, + "node_modules/alpinejs": { +- "version": "3.17.1", +- "resolved": "https://registry.npmjs.org/alpinejs/-/alpinejs-3.17.1.tgz", +- "integrity": "sha512-HDUhA9juSA/pNYZ5FAAlW4qNsdeVORFSVONEIu0hVasqCOqLitf15R9tCr5GBCV0ZxiZW2Qx6BYdMSF7iGLT/Q==", ++ "version": "3.17.2", ++ "resolved": "https://registry.npmjs.org/alpinejs/-/alpinejs-3.17.2.tgz", ++ "integrity": "sha512-xbnG3LlnmFkiNO49C+qhqjEDqOdB0snKqvT48ZVp8TakpZOpsoQbc/jAxpptQRjZi7c9rLeCfvwQ/XOSirIZFQ==", + "license": "MIT", + "dependencies": { + "@vue/reactivity": "~3.5.40" diff --git a/tasks/livewire__livewire-10676/tests/test.sh b/tasks/livewire__livewire-10676/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3c2206bc2f8e545ae3abaedff882e2b978bc21dc --- /dev/null +++ b/tasks/livewire__livewire-10676/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 3da3c48c7c98672af7289646b1e65288aed83ebb > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/livewire__livewire-10676/tests/verifier.py b/tasks/livewire__livewire-10676/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/livewire__livewire-10676/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/livewire__livewire-10677/environment/Dockerfile b/tasks/livewire__livewire-10677/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..7b5c758cff9bf491a1d680a57dc246a539fca554 --- /dev/null +++ b/tasks/livewire__livewire-10677/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/livewire/livewire.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/livewire/livewire.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/livewire/livewire.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4bedc452f1b5b71bcf4d2ced100e708b882ff42a 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4bedc452f1b5b71bcf4d2ced100e708b882ff42a \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4bedc452f1b5b71bcf4d2ced100e708b882ff42a \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/livewire__livewire-10677/instruction.md b/tasks/livewire__livewire-10677/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..cd30e6ce37b267857208213181606223543a85d4 --- /dev/null +++ b/tasks/livewire__livewire-10677/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** Update Alpine 3.17.2 lockfile on main + +## Description + +Updates `package-lock.json` to match the Alpine 3.17.2 constraints already merged in #10671. + +This fixes the exact-head `npm ci` failure on main. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4bedc452f1b5`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10677/solution/patch.diff b/tasks/livewire__livewire-10677/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..b7ca5539d3d424f208514f714013bc11378d1be6 --- /dev/null +++ b/tasks/livewire__livewire-10677/solution/patch.diff @@ -0,0 +1,151 @@ +diff --git a/package-lock.json b/package-lock.json +index 9dcd46c9..2f324395 100644 +--- a/package-lock.json ++++ b/package-lock.json +@@ -7,18 +7,18 @@ + "name": "laravel-livewire", + "license": "MIT", + "dependencies": { +- "@alpinejs/anchor": "^3.17.1", +- "@alpinejs/collapse": "^3.17.1", +- "@alpinejs/csp": "^3.17.1", +- "@alpinejs/focus": "^3.17.1", +- "@alpinejs/intersect": "^3.17.1", +- "@alpinejs/mask": "^3.17.1", +- "@alpinejs/morph": "^3.17.1", +- "@alpinejs/persist": "^3.17.1", +- "@alpinejs/resize": "^3.17.1", +- "@alpinejs/sort": "^3.17.1", ++ "@alpinejs/anchor": "^3.17.2", ++ "@alpinejs/collapse": "^3.17.2", ++ "@alpinejs/csp": "^3.17.2", ++ "@alpinejs/focus": "^3.17.2", ++ "@alpinejs/intersect": "^3.17.2", ++ "@alpinejs/mask": "^3.17.2", ++ "@alpinejs/morph": "^3.17.2", ++ "@alpinejs/persist": "^3.17.2", ++ "@alpinejs/resize": "^3.17.2", ++ "@alpinejs/sort": "^3.17.2", + "@vue/reactivity": "^3.2.45", +- "alpinejs": "^3.17.1", ++ "alpinejs": "^3.17.2", + "nprogress": "^0.2.0" + }, + "devDependencies": { +@@ -29,33 +29,33 @@ + } + }, + "node_modules/@alpinejs/anchor": { +- "version": "3.17.1", +- "resolved": "https://registry.npmjs.org/@alpinejs/anchor/-/anchor-3.17.1.tgz", +- "integrity": "sha512-x6mVH3CAUKLMMh1jEgJ7pWi9DzKEgTq6pK391wN1MvSLndjr0RYOyfCakS1Y6SqHZbTyRtwfp3zG3ECoFYILKw==", ++ "version": "3.17.2", ++ "resolved": "https://registry.npmjs.org/@alpinejs/anchor/-/anchor-3.17.2.tgz", ++ "integrity": "sha512-b4I/HwzG6o1L1hOcuGSxDuFUVJH4MgKWC+xr5fxWvUNeqqsTyB0ioqhfcqoA0vvIFnm9eLhGuwiKt4FymZis0A==", + "license": "MIT", + "dependencies": { + "@floating-ui/dom": "^1.5.3" + } + }, + "node_modules/@alpinejs/collapse": { +- "version": "3.17.1", +- "resolved": "https://registry.npmjs.org/@alpinejs/collapse/-/collapse-3.17.1.tgz", +- "integrity": "sha512-ygf0kJ2I+1TgBUjS+V1Dx2KlT/y/AatyfavzL7b2T3qrPx7WRGI4yxvFB0h6J5OZVO08dhtDTVk/Z1GIC6ME/w==", ++ "version": "3.17.2", ++ "resolved": "https://registry.npmjs.org/@alpinejs/collapse/-/collapse-3.17.2.tgz", ++ "integrity": "sha512-OugjrAUGXkg8Msmitgf3rXFyoSYXchN00LPQYC2zDjaTcuRaVXXseBZcCU7DZ7b6cyZzCvYbIYngbaaEzvEfuw==", + "license": "MIT" + }, + "node_modules/@alpinejs/csp": { +- "version": "3.17.1", +- "resolved": "https://registry.npmjs.org/@alpinejs/csp/-/csp-3.17.1.tgz", +- "integrity": "sha512-HDrY0ZxvJWSmeUYqtHVSsitaqy1es3VDCNodPpdQRX4nHhHiRoeib+rOzRFFStFRD/6x0KmQzJVJ4FCLAI/DUQ==", ++ "version": "3.17.2", ++ "resolved": "https://registry.npmjs.org/@alpinejs/csp/-/csp-3.17.2.tgz", ++ "integrity": "sha512-jJXIzBaplTu1xVuhtNXEYDQDbQrdVJbXHYSVeF22fz4Vzm+g0X2XMb4pY1ywEpYLsFRx7ZcBE5gMyyuJpKPfHg==", + "license": "MIT", + "dependencies": { + "@vue/reactivity": "~3.5.40" + } + }, + "node_modules/@alpinejs/focus": { +- "version": "3.17.1", +- "resolved": "https://registry.npmjs.org/@alpinejs/focus/-/focus-3.17.1.tgz", +- "integrity": "sha512-23+9xUfPMhuqIm6xeqLQmQTBjNY/yHtJ5np05WrFZLdKXOXCLktpAE7ZAgmPoD/s7F2banEiJzTSFDO6GnWUIg==", ++ "version": "3.17.2", ++ "resolved": "https://registry.npmjs.org/@alpinejs/focus/-/focus-3.17.2.tgz", ++ "integrity": "sha512-ZYER+iuYu9IHT2ihAaP04alQLzLzH5nEMmFwVDe7Yu6bzeub+yJISYjR2hH+DlQTcmAZc7xnFMb6zscCVI091Q==", + "license": "MIT", + "dependencies": { + "focus-trap": "^8.0.0", +@@ -63,39 +63,39 @@ + } + }, + "node_modules/@alpinejs/intersect": { +- "version": "3.17.1", +- "resolved": "https://registry.npmjs.org/@alpinejs/intersect/-/intersect-3.17.1.tgz", +- "integrity": "sha512-60UZyk6BNGocHgEvKxBfgqPXq9Y1tuQ363/FjdlXc1eNI8Q0arelStWLhEyd0u8JJp7FTr50S/CmaYXMijTQYQ==", ++ "version": "3.17.2", ++ "resolved": "https://registry.npmjs.org/@alpinejs/intersect/-/intersect-3.17.2.tgz", ++ "integrity": "sha512-q4AJZDk7l/q7PaLeacMmdCfCCtgU3Qve9QTt4t6+A0z8F3YU2xqku08O9N7IENwiPKxlWseqXWWSlr97FSyZ9w==", + "license": "MIT" + }, + "node_modules/@alpinejs/mask": { +- "version": "3.17.1", +- "resolved": "https://registry.npmjs.org/@alpinejs/mask/-/mask-3.17.1.tgz", +- "integrity": "sha512-EK/6nkVdO0kyLM/xYag6oJ2jEbQevEfsdRdjUnwJnzCcLLulUpTLo0JVRBml9XBobM614pVOEMzdbXPPI0wB9w==", ++ "version": "3.17.2", ++ "resolved": "https://registry.npmjs.org/@alpinejs/mask/-/mask-3.17.2.tgz", ++ "integrity": "sha512-o2ht803nXshsYyNFvR4cUg/9XijF9eqwN8FFEVJUxriVJRS5jWDVADjijHcjQuVKGJYmzdnUMSLBPv48F8In9Q==", + "license": "MIT" + }, + "node_modules/@alpinejs/morph": { +- "version": "3.17.1", +- "resolved": "https://registry.npmjs.org/@alpinejs/morph/-/morph-3.17.1.tgz", +- "integrity": "sha512-RVafJn9fsF1mrxbQniSgTyneV4ybEFPgBGsjwpxko1g0WPdctTewgnxxO86gy5VztpjNvpjRW1bcpq39WtMt8w==", ++ "version": "3.17.2", ++ "resolved": "https://registry.npmjs.org/@alpinejs/morph/-/morph-3.17.2.tgz", ++ "integrity": "sha512-9O+m1ChwU3JNFsTY7WDAOdG3qPYmE5zJp+2XWX/ymc57S9ifmmx0RCnRR/14CPEqTc/cdpUIOlnAGBg0NAGHpw==", + "license": "MIT" + }, + "node_modules/@alpinejs/persist": { +- "version": "3.17.1", +- "resolved": "https://registry.npmjs.org/@alpinejs/persist/-/persist-3.17.1.tgz", +- "integrity": "sha512-PN/93FIWakZYY4zB/VGDlFtx2LOoa318huflgLMo2jsk+pkjLlDkX1qmuUFh5xhI7Uj3vSvU1Eu1WIA3TN3PTA==", ++ "version": "3.17.2", ++ "resolved": "https://registry.npmjs.org/@alpinejs/persist/-/persist-3.17.2.tgz", ++ "integrity": "sha512-BN8v27efELn2IgWjFoY0IkUmT1JOt3gUwEIb+2rjCU875E6VDbc6n0d29l9giITRgqyugm00H/xB1kcPVrQlcQ==", + "license": "MIT" + }, + "node_modules/@alpinejs/resize": { +- "version": "3.17.1", +- "resolved": "https://registry.npmjs.org/@alpinejs/resize/-/resize-3.17.1.tgz", +- "integrity": "sha512-TyHYMY6DQBh9P/hOFH3KGLE7ilyfR3u3qsYtJfpsE6Fq8eKobkjudahmhHmdiGurohx8YaVbWBNilDcnAjLOTw==", ++ "version": "3.17.2", ++ "resolved": "https://registry.npmjs.org/@alpinejs/resize/-/resize-3.17.2.tgz", ++ "integrity": "sha512-6v/LECG5pHMh/5iAY/PSPilZZtgt6kVmbpTTyLScmusIt1wyGqbX/wLXJnJwnr40Swb3B4ZImEBK9r1+GDlC8g==", + "license": "MIT" + }, + "node_modules/@alpinejs/sort": { +- "version": "3.17.1", +- "resolved": "https://registry.npmjs.org/@alpinejs/sort/-/sort-3.17.1.tgz", +- "integrity": "sha512-Q6qF00WI4cQAZdIxPgbsHnxZIiIv4T1kfSPyEy2QB/SLhLdISuIjzTBa3TQAe1P45BkRtNk5Y8fQuDZuKhN/6w==", ++ "version": "3.17.2", ++ "resolved": "https://registry.npmjs.org/@alpinejs/sort/-/sort-3.17.2.tgz", ++ "integrity": "sha512-72v63zuFkepgO2nwi8wNrD1z6pAY3S+d+lCwSZ9Q39hkIFISxPXKffEh3qtTu7Dzlc98EYLz4kVS/pxp3mdw5g==", + "license": "MIT", + "dependencies": { + "sortablejs": "^1.15.2" +@@ -1266,9 +1266,9 @@ + } + }, + "node_modules/alpinejs": { +- "version": "3.17.1", +- "resolved": "https://registry.npmjs.org/alpinejs/-/alpinejs-3.17.1.tgz", +- "integrity": "sha512-HDUhA9juSA/pNYZ5FAAlW4qNsdeVORFSVONEIu0hVasqCOqLitf15R9tCr5GBCV0ZxiZW2Qx6BYdMSF7iGLT/Q==", ++ "version": "3.17.2", ++ "resolved": "https://registry.npmjs.org/alpinejs/-/alpinejs-3.17.2.tgz", ++ "integrity": "sha512-xbnG3LlnmFkiNO49C+qhqjEDqOdB0snKqvT48ZVp8TakpZOpsoQbc/jAxpptQRjZi7c9rLeCfvwQ/XOSirIZFQ==", + "license": "MIT", + "dependencies": { + "@vue/reactivity": "~3.5.40" diff --git a/tasks/livewire__livewire-10677/solution/solve.sh b/tasks/livewire__livewire-10677/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/livewire__livewire-10677/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/livewire__livewire-10677/task.toml b/tasks/livewire__livewire-10677/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..784348f3201b9871ae8bcc3083f514c4da0d6ae4 --- /dev/null +++ b/tasks/livewire__livewire-10677/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/livewire__livewire-10677" +description = "Update Alpine 3.17.2 lockfile on main" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "livewire", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "livewire/livewire" +ref = "4bedc452f1b5b71bcf4d2ced100e708b882ff42a" +reference = "https://github.com/livewire/livewire/pull/10677" +source_access = "auto" +built_at = "2026-11-16T16:09:51.502208+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:4e936575ba6e6bea6b085d5fbe0fa4e6a1d7da975f631e8fa01441bd8f389086" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-07T15:32:56Z" +diff_format = "unified" +context_files = [ + "package-lock.json", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 88 +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.409315+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:75f5052da2f08ea3b6f548333d9b8583b2afa810c1978745798c15d70c252b16" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/livewire__livewire-10677/tests/capture.py b/tasks/livewire__livewire-10677/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/livewire__livewire-10677/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/livewire__livewire-10677/tests/instruction.md b/tasks/livewire__livewire-10677/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..cd30e6ce37b267857208213181606223543a85d4 --- /dev/null +++ b/tasks/livewire__livewire-10677/tests/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** Update Alpine 3.17.2 lockfile on main + +## Description + +Updates `package-lock.json` to match the Alpine 3.17.2 constraints already merged in #10671. + +This fixes the exact-head `npm ci` failure on main. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4bedc452f1b5`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10677/tests/oracle.patch b/tasks/livewire__livewire-10677/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..b7ca5539d3d424f208514f714013bc11378d1be6 --- /dev/null +++ b/tasks/livewire__livewire-10677/tests/oracle.patch @@ -0,0 +1,151 @@ +diff --git a/package-lock.json b/package-lock.json +index 9dcd46c9..2f324395 100644 +--- a/package-lock.json ++++ b/package-lock.json +@@ -7,18 +7,18 @@ + "name": "laravel-livewire", + "license": "MIT", + "dependencies": { +- "@alpinejs/anchor": "^3.17.1", +- "@alpinejs/collapse": "^3.17.1", +- "@alpinejs/csp": "^3.17.1", +- "@alpinejs/focus": "^3.17.1", +- "@alpinejs/intersect": "^3.17.1", +- "@alpinejs/mask": "^3.17.1", +- "@alpinejs/morph": "^3.17.1", +- "@alpinejs/persist": "^3.17.1", +- "@alpinejs/resize": "^3.17.1", +- "@alpinejs/sort": "^3.17.1", ++ "@alpinejs/anchor": "^3.17.2", ++ "@alpinejs/collapse": "^3.17.2", ++ "@alpinejs/csp": "^3.17.2", ++ "@alpinejs/focus": "^3.17.2", ++ "@alpinejs/intersect": "^3.17.2", ++ "@alpinejs/mask": "^3.17.2", ++ "@alpinejs/morph": "^3.17.2", ++ "@alpinejs/persist": "^3.17.2", ++ "@alpinejs/resize": "^3.17.2", ++ "@alpinejs/sort": "^3.17.2", + "@vue/reactivity": "^3.2.45", +- "alpinejs": "^3.17.1", ++ "alpinejs": "^3.17.2", + "nprogress": "^0.2.0" + }, + "devDependencies": { +@@ -29,33 +29,33 @@ + } + }, + "node_modules/@alpinejs/anchor": { +- "version": "3.17.1", +- "resolved": "https://registry.npmjs.org/@alpinejs/anchor/-/anchor-3.17.1.tgz", +- "integrity": "sha512-x6mVH3CAUKLMMh1jEgJ7pWi9DzKEgTq6pK391wN1MvSLndjr0RYOyfCakS1Y6SqHZbTyRtwfp3zG3ECoFYILKw==", ++ "version": "3.17.2", ++ "resolved": "https://registry.npmjs.org/@alpinejs/anchor/-/anchor-3.17.2.tgz", ++ "integrity": "sha512-b4I/HwzG6o1L1hOcuGSxDuFUVJH4MgKWC+xr5fxWvUNeqqsTyB0ioqhfcqoA0vvIFnm9eLhGuwiKt4FymZis0A==", + "license": "MIT", + "dependencies": { + "@floating-ui/dom": "^1.5.3" + } + }, + "node_modules/@alpinejs/collapse": { +- "version": "3.17.1", +- "resolved": "https://registry.npmjs.org/@alpinejs/collapse/-/collapse-3.17.1.tgz", +- "integrity": "sha512-ygf0kJ2I+1TgBUjS+V1Dx2KlT/y/AatyfavzL7b2T3qrPx7WRGI4yxvFB0h6J5OZVO08dhtDTVk/Z1GIC6ME/w==", ++ "version": "3.17.2", ++ "resolved": "https://registry.npmjs.org/@alpinejs/collapse/-/collapse-3.17.2.tgz", ++ "integrity": "sha512-OugjrAUGXkg8Msmitgf3rXFyoSYXchN00LPQYC2zDjaTcuRaVXXseBZcCU7DZ7b6cyZzCvYbIYngbaaEzvEfuw==", + "license": "MIT" + }, + "node_modules/@alpinejs/csp": { +- "version": "3.17.1", +- "resolved": "https://registry.npmjs.org/@alpinejs/csp/-/csp-3.17.1.tgz", +- "integrity": "sha512-HDrY0ZxvJWSmeUYqtHVSsitaqy1es3VDCNodPpdQRX4nHhHiRoeib+rOzRFFStFRD/6x0KmQzJVJ4FCLAI/DUQ==", ++ "version": "3.17.2", ++ "resolved": "https://registry.npmjs.org/@alpinejs/csp/-/csp-3.17.2.tgz", ++ "integrity": "sha512-jJXIzBaplTu1xVuhtNXEYDQDbQrdVJbXHYSVeF22fz4Vzm+g0X2XMb4pY1ywEpYLsFRx7ZcBE5gMyyuJpKPfHg==", + "license": "MIT", + "dependencies": { + "@vue/reactivity": "~3.5.40" + } + }, + "node_modules/@alpinejs/focus": { +- "version": "3.17.1", +- "resolved": "https://registry.npmjs.org/@alpinejs/focus/-/focus-3.17.1.tgz", +- "integrity": "sha512-23+9xUfPMhuqIm6xeqLQmQTBjNY/yHtJ5np05WrFZLdKXOXCLktpAE7ZAgmPoD/s7F2banEiJzTSFDO6GnWUIg==", ++ "version": "3.17.2", ++ "resolved": "https://registry.npmjs.org/@alpinejs/focus/-/focus-3.17.2.tgz", ++ "integrity": "sha512-ZYER+iuYu9IHT2ihAaP04alQLzLzH5nEMmFwVDe7Yu6bzeub+yJISYjR2hH+DlQTcmAZc7xnFMb6zscCVI091Q==", + "license": "MIT", + "dependencies": { + "focus-trap": "^8.0.0", +@@ -63,39 +63,39 @@ + } + }, + "node_modules/@alpinejs/intersect": { +- "version": "3.17.1", +- "resolved": "https://registry.npmjs.org/@alpinejs/intersect/-/intersect-3.17.1.tgz", +- "integrity": "sha512-60UZyk6BNGocHgEvKxBfgqPXq9Y1tuQ363/FjdlXc1eNI8Q0arelStWLhEyd0u8JJp7FTr50S/CmaYXMijTQYQ==", ++ "version": "3.17.2", ++ "resolved": "https://registry.npmjs.org/@alpinejs/intersect/-/intersect-3.17.2.tgz", ++ "integrity": "sha512-q4AJZDk7l/q7PaLeacMmdCfCCtgU3Qve9QTt4t6+A0z8F3YU2xqku08O9N7IENwiPKxlWseqXWWSlr97FSyZ9w==", + "license": "MIT" + }, + "node_modules/@alpinejs/mask": { +- "version": "3.17.1", +- "resolved": "https://registry.npmjs.org/@alpinejs/mask/-/mask-3.17.1.tgz", +- "integrity": "sha512-EK/6nkVdO0kyLM/xYag6oJ2jEbQevEfsdRdjUnwJnzCcLLulUpTLo0JVRBml9XBobM614pVOEMzdbXPPI0wB9w==", ++ "version": "3.17.2", ++ "resolved": "https://registry.npmjs.org/@alpinejs/mask/-/mask-3.17.2.tgz", ++ "integrity": "sha512-o2ht803nXshsYyNFvR4cUg/9XijF9eqwN8FFEVJUxriVJRS5jWDVADjijHcjQuVKGJYmzdnUMSLBPv48F8In9Q==", + "license": "MIT" + }, + "node_modules/@alpinejs/morph": { +- "version": "3.17.1", +- "resolved": "https://registry.npmjs.org/@alpinejs/morph/-/morph-3.17.1.tgz", +- "integrity": "sha512-RVafJn9fsF1mrxbQniSgTyneV4ybEFPgBGsjwpxko1g0WPdctTewgnxxO86gy5VztpjNvpjRW1bcpq39WtMt8w==", ++ "version": "3.17.2", ++ "resolved": "https://registry.npmjs.org/@alpinejs/morph/-/morph-3.17.2.tgz", ++ "integrity": "sha512-9O+m1ChwU3JNFsTY7WDAOdG3qPYmE5zJp+2XWX/ymc57S9ifmmx0RCnRR/14CPEqTc/cdpUIOlnAGBg0NAGHpw==", + "license": "MIT" + }, + "node_modules/@alpinejs/persist": { +- "version": "3.17.1", +- "resolved": "https://registry.npmjs.org/@alpinejs/persist/-/persist-3.17.1.tgz", +- "integrity": "sha512-PN/93FIWakZYY4zB/VGDlFtx2LOoa318huflgLMo2jsk+pkjLlDkX1qmuUFh5xhI7Uj3vSvU1Eu1WIA3TN3PTA==", ++ "version": "3.17.2", ++ "resolved": "https://registry.npmjs.org/@alpinejs/persist/-/persist-3.17.2.tgz", ++ "integrity": "sha512-BN8v27efELn2IgWjFoY0IkUmT1JOt3gUwEIb+2rjCU875E6VDbc6n0d29l9giITRgqyugm00H/xB1kcPVrQlcQ==", + "license": "MIT" + }, + "node_modules/@alpinejs/resize": { +- "version": "3.17.1", +- "resolved": "https://registry.npmjs.org/@alpinejs/resize/-/resize-3.17.1.tgz", +- "integrity": "sha512-TyHYMY6DQBh9P/hOFH3KGLE7ilyfR3u3qsYtJfpsE6Fq8eKobkjudahmhHmdiGurohx8YaVbWBNilDcnAjLOTw==", ++ "version": "3.17.2", ++ "resolved": "https://registry.npmjs.org/@alpinejs/resize/-/resize-3.17.2.tgz", ++ "integrity": "sha512-6v/LECG5pHMh/5iAY/PSPilZZtgt6kVmbpTTyLScmusIt1wyGqbX/wLXJnJwnr40Swb3B4ZImEBK9r1+GDlC8g==", + "license": "MIT" + }, + "node_modules/@alpinejs/sort": { +- "version": "3.17.1", +- "resolved": "https://registry.npmjs.org/@alpinejs/sort/-/sort-3.17.1.tgz", +- "integrity": "sha512-Q6qF00WI4cQAZdIxPgbsHnxZIiIv4T1kfSPyEy2QB/SLhLdISuIjzTBa3TQAe1P45BkRtNk5Y8fQuDZuKhN/6w==", ++ "version": "3.17.2", ++ "resolved": "https://registry.npmjs.org/@alpinejs/sort/-/sort-3.17.2.tgz", ++ "integrity": "sha512-72v63zuFkepgO2nwi8wNrD1z6pAY3S+d+lCwSZ9Q39hkIFISxPXKffEh3qtTu7Dzlc98EYLz4kVS/pxp3mdw5g==", + "license": "MIT", + "dependencies": { + "sortablejs": "^1.15.2" +@@ -1266,9 +1266,9 @@ + } + }, + "node_modules/alpinejs": { +- "version": "3.17.1", +- "resolved": "https://registry.npmjs.org/alpinejs/-/alpinejs-3.17.1.tgz", +- "integrity": "sha512-HDUhA9juSA/pNYZ5FAAlW4qNsdeVORFSVONEIu0hVasqCOqLitf15R9tCr5GBCV0ZxiZW2Qx6BYdMSF7iGLT/Q==", ++ "version": "3.17.2", ++ "resolved": "https://registry.npmjs.org/alpinejs/-/alpinejs-3.17.2.tgz", ++ "integrity": "sha512-xbnG3LlnmFkiNO49C+qhqjEDqOdB0snKqvT48ZVp8TakpZOpsoQbc/jAxpptQRjZi7c9rLeCfvwQ/XOSirIZFQ==", + "license": "MIT", + "dependencies": { + "@vue/reactivity": "~3.5.40" diff --git a/tasks/livewire__livewire-10677/tests/test.sh b/tasks/livewire__livewire-10677/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..c4addcd9bd357fad12e2ea123013d6bb07df40ca --- /dev/null +++ b/tasks/livewire__livewire-10677/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 4bedc452f1b5b71bcf4d2ced100e708b882ff42a > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/livewire__livewire-10677/tests/verifier.py b/tasks/livewire__livewire-10677/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/livewire__livewire-10677/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/livewire__livewire-10682/environment/Dockerfile b/tasks/livewire__livewire-10682/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a2b6881f44f825e2ace029579c3f170f3118a23f --- /dev/null +++ b/tasks/livewire__livewire-10682/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/livewire/livewire.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/livewire/livewire.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/livewire/livewire.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 76c76760242aa690abd0db451cd7a32b4c360adb 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 76c76760242aa690abd0db451cd7a32b4c360adb \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 76c76760242aa690abd0db451cd7a32b4c360adb \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/livewire__livewire-10682/instruction.md b/tasks/livewire__livewire-10682/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..02774a58cc3e0361468f1a17744d04514151e8b4 --- /dev/null +++ b/tasks/livewire__livewire-10682/instruction.md @@ -0,0 +1,50 @@ +# Issue + +**Title:** [4.x] Preserve non-HTML attribute for blade props + +## Description + +## Summary + +Fix a regression where array and object values passed to a Livewire component could no longer be used with Blade's `@props` directive. + +## Problem + +Values passed to a component that weren't defined as component properties were being treated as HTML attributes. + +After a recent fix () to prevent arrays and objects from being rendered as HTML attributes, those values were also no longer available to `@props`. + +For example: + +```blade +@props(['rows' => []]) + +@foreach ($rows as $row) + ... +@endforeach +``` + +If `rows` was passed from the parent, the component would incorrectly receive the default empty array instead of the provided rows. + +## Solution + +Non-HTML values are now still available to the component view, so they can be used with `@props`. + +At the same time, they are not rendered as HTML attributes. + +Regular HTML attributes such as `id` and `class` continue to work as before. + +## Tests + +Added coverage for: + +* Using non-HTML values with `@props` +* Using `@props` without a default value +* Ensuring non-HTML values are not rendered as HTML attributes +* Ensuring regular HTML attributes continue to be forwarded correctly + +Fixes: + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `76c76760242a`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10682/solution/patch.diff b/tasks/livewire__livewire-10682/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..f742d0261f73a2e7603c5270ad5c317100414b0f --- /dev/null +++ b/tasks/livewire__livewire-10682/solution/patch.diff @@ -0,0 +1,215 @@ +diff --git a/src/Features/SupportHtmlAttributeForwarding/HandlesHtmlAttributeForwarding.php b/src/Features/SupportHtmlAttributeForwarding/HandlesHtmlAttributeForwarding.php +index 14d95025..c03b3521 100644 +--- a/src/Features/SupportHtmlAttributeForwarding/HandlesHtmlAttributeForwarding.php ++++ b/src/Features/SupportHtmlAttributeForwarding/HandlesHtmlAttributeForwarding.php +@@ -24,4 +24,9 @@ trait HandlesHtmlAttributeForwarding + fn ($value) => is_scalar($value) || is_null($value) || $value instanceof Htmlable + ); + } ++ ++ public function getNonHtmlAttributes(): array ++ { ++ return array_diff_key($this->htmlAttributes, $this->getHtmlAttributes()); ++ } + } +diff --git a/src/Features/SupportHtmlAttributeForwarding/SupportHtmlAttributeForwarding.php b/src/Features/SupportHtmlAttributeForwarding/SupportHtmlAttributeForwarding.php +index 9279e324..e50b028a 100644 +--- a/src/Features/SupportHtmlAttributeForwarding/SupportHtmlAttributeForwarding.php ++++ b/src/Features/SupportHtmlAttributeForwarding/SupportHtmlAttributeForwarding.php +@@ -9,23 +9,17 @@ class SupportHtmlAttributeForwarding extends ComponentHook + { + public function render($view, $properties) + { +- $attributes = $this->component->getHtmlAttributes(); +- +- $view->with(['attributes' => new ComponentAttributeBag($attributes)]); ++ $this->forwardAttributesToView($view); + } + + public function renderIsland($name, $view, $properties) + { +- $attributes = $this->component->getHtmlAttributes(); +- +- $view->with(['attributes' => new ComponentAttributeBag($attributes)]); ++ $this->forwardAttributesToView($view); + } + + public function renderPlaceholder($view, $properties) + { +- $attributes = $this->component->getHtmlAttributes(); +- +- $view->with(['attributes' => new ComponentAttributeBag($attributes)]); ++ $this->forwardAttributesToView($view); + } + + function hydrate($memo) +@@ -45,4 +39,13 @@ class SupportHtmlAttributeForwarding extends ComponentHook + $context->addMemo('attributes', $attributes); + } + } +-} +\ No newline at end of file ++ ++ protected function forwardAttributesToView($view) ++ { ++ $attributes = $this->component->getHtmlAttributes(); ++ ++ $view->with($this->component->getNonHtmlAttributes()); ++ ++ $view->with(['attributes' => new ComponentAttributeBag($attributes)]); ++ } ++} +diff --git a/src/Features/SupportHtmlAttributeForwarding/UnitTest.php b/src/Features/SupportHtmlAttributeForwarding/UnitTest.php +index 507be6cb..3e17a0a4 100644 +--- a/src/Features/SupportHtmlAttributeForwarding/UnitTest.php ++++ b/src/Features/SupportHtmlAttributeForwarding/UnitTest.php +@@ -193,6 +193,89 @@ class UnitTest extends TestCase + $this->assertStringNotContainsString('first@example.com', $html); + $this->assertStringNotContainsString('pageFilters', $html); + } ++ ++ public function test_non_html_attributes_are_available_to_blade_props() ++ { ++ Livewire::component('alert', AlertWithProps::class); ++ ++ $html = Livewire::mount('alert', [ ++ 'rows' => [ ++ ['id' => 1, 'name' => 'Alice'], ++ ['id' => 2, 'name' => 'Bob'], ++ ], ++ 'id' => 'rows-component', ++ ]); ++ ++ $this->assertStringContainsString('Alice', $html); ++ $this->assertStringContainsString('Bob', $html); ++ $this->assertStringContainsString('id="rows-component"', $html); ++ $this->assertStringNotContainsString('rows=', $html); ++ } ++ ++ public function test_non_html_attributes_are_available_as_blade_props_without_default() ++ { ++ Livewire::component('alert', AlertWithPropsWithoutDefault::class); ++ ++ $html = Livewire::mount('alert', [ ++ 'rows' => [ ++ ['id' => 1, 'name' => 'Alice'], ++ ], ++ 'id' => 'rows-component', ++ ]); ++ ++ $this->assertStringContainsString('Alice', $html); ++ $this->assertStringContainsString('id="rows-component"', $html); ++ $this->assertStringNotContainsString('rows=', $html); ++ } ++ ++ public function test_html_attributes_are_forwarded_while_non_html_attributes_are_available_as_blade_props() ++ { ++ Livewire::component('alert', AlertWithProps::class); ++ ++ $html = Livewire::mount('alert', [ ++ 'rows' => [ ++ ['id' => 1, 'name' => 'Alice'], ++ ], ++ 'id' => 'rows-component', ++ ]); ++ ++ $this->assertStringContainsString('Alice', $html); ++ $this->assertStringContainsString('id="rows-component"', $html); ++ $this->assertStringNotContainsString('rows="', $html); ++ } ++ ++ public function test_non_html_attributes_are_available_as_blade_props_in_placeholder() ++ { ++ SupportLazyLoading::$disableWhileTesting = false; ++ ++ Livewire::component('alert', LazyAlertWithProps::class); ++ ++ $html = Livewire::mount('alert', [ ++ 'lazy' => true, ++ 'rows' => [ ++ ['id' => 1, 'name' => 'Alice'], ++ ], ++ 'id' => 'rows-component', ++ ]); ++ ++ $this->assertStringContainsString('Alice', $html); ++ $this->assertStringContainsString('id="rows-component"', $html); ++ $this->assertStringNotContainsString('rows=', $html); ++ } ++ ++ public function test_eloquent_model_are_available_as_blade_props_without_being_dehydrated() ++ { ++ Livewire::component('alert', AlertWithRecordProps::class); ++ ++ $html = Livewire::mount('alert', [ ++ 'record' => RecordModel::first(), ++ 'id' => 'rows-component', ++ ]); ++ ++ $this->assertStringContainsString('First User', $html); ++ $this->assertStringContainsString('id="rows-component"', $html); ++ $this->assertStringNotContainsString('first@example.com', $html); ++ } + } + + class RecordModel extends Model +@@ -239,3 +322,59 @@ class AlertWithIslandAttributes extends Component + HTML; + } + } ++ ++class AlertWithProps extends Component ++{ ++ public function render() ++ { ++ return <<<'HTML' ++ @props(['rows' => []]) ++
    ++ @foreach ($rows as $row) ++
  • {{ $row['name'] }}
  • ++ @endforeach ++
++ HTML; ++ } ++} ++ ++class AlertWithPropsWithoutDefault extends Component ++{ ++ public function render() ++ { ++ return <<<'HTML' ++ @props(['rows']) ++
++ {{ $rows[0]['name'] }} ++
++ HTML; ++ } ++} ++ ++#[Lazy] ++class LazyAlertWithProps extends Component ++{ ++ public function placeholder() ++ { ++ return <<<'HTML' ++ @props(['rows']) ++
{{ $rows[0]['name'] }}
++ HTML; ++ } ++ ++ public function render() ++ { ++ return '
Alert
'; ++ } ++} ++ ++class AlertWithRecordProps extends Component ++{ ++ public function render() ++ { ++ return <<<'HTML' ++ @props(['record']) ++
{{ $record->name }}
++ HTML; ++ } ++} diff --git a/tasks/livewire__livewire-10682/solution/solve.sh b/tasks/livewire__livewire-10682/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/livewire__livewire-10682/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/livewire__livewire-10682/task.toml b/tasks/livewire__livewire-10682/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..4c084ec60e2baf9ec9c52b007132f0740c75f770 --- /dev/null +++ b/tasks/livewire__livewire-10682/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/livewire__livewire-10682" +description = "[4.x] Preserve non-HTML attribute for blade props" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "livewire", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "livewire/livewire" +ref = "76c76760242aa690abd0db451cd7a32b4c360adb" +reference = "https://github.com/livewire/livewire/pull/10682" +source_access = "auto" +built_at = "2026-11-16T16:09:51.500631+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:9b8456a1a82d25456f66de3fc9a7fb316a1ed3545cabc8a7bbe0a829b54d100f" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-09T12:46:17Z" +diff_format = "unified" +context_files = [ + "src/Features/SupportHtmlAttributeForwarding/HandlesHtmlAttributeForwarding.php", + "src/Features/SupportHtmlAttributeForwarding/SupportHtmlAttributeForwarding.php", + "src/Features/SupportHtmlAttributeForwarding/UnitTest.php", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 167 +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.409828+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:5d2c9ea03452f1bdcf2edfbac4ca2ebf5c06839e67c856e931938da9f590ee6e" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/livewire__livewire-10682/tests/capture.py b/tasks/livewire__livewire-10682/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/livewire__livewire-10682/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/livewire__livewire-10682/tests/instruction.md b/tasks/livewire__livewire-10682/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..02774a58cc3e0361468f1a17744d04514151e8b4 --- /dev/null +++ b/tasks/livewire__livewire-10682/tests/instruction.md @@ -0,0 +1,50 @@ +# Issue + +**Title:** [4.x] Preserve non-HTML attribute for blade props + +## Description + +## Summary + +Fix a regression where array and object values passed to a Livewire component could no longer be used with Blade's `@props` directive. + +## Problem + +Values passed to a component that weren't defined as component properties were being treated as HTML attributes. + +After a recent fix () to prevent arrays and objects from being rendered as HTML attributes, those values were also no longer available to `@props`. + +For example: + +```blade +@props(['rows' => []]) + +@foreach ($rows as $row) + ... +@endforeach +``` + +If `rows` was passed from the parent, the component would incorrectly receive the default empty array instead of the provided rows. + +## Solution + +Non-HTML values are now still available to the component view, so they can be used with `@props`. + +At the same time, they are not rendered as HTML attributes. + +Regular HTML attributes such as `id` and `class` continue to work as before. + +## Tests + +Added coverage for: + +* Using non-HTML values with `@props` +* Using `@props` without a default value +* Ensuring non-HTML values are not rendered as HTML attributes +* Ensuring regular HTML attributes continue to be forwarded correctly + +Fixes: + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `76c76760242a`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10682/tests/oracle.patch b/tasks/livewire__livewire-10682/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..f742d0261f73a2e7603c5270ad5c317100414b0f --- /dev/null +++ b/tasks/livewire__livewire-10682/tests/oracle.patch @@ -0,0 +1,215 @@ +diff --git a/src/Features/SupportHtmlAttributeForwarding/HandlesHtmlAttributeForwarding.php b/src/Features/SupportHtmlAttributeForwarding/HandlesHtmlAttributeForwarding.php +index 14d95025..c03b3521 100644 +--- a/src/Features/SupportHtmlAttributeForwarding/HandlesHtmlAttributeForwarding.php ++++ b/src/Features/SupportHtmlAttributeForwarding/HandlesHtmlAttributeForwarding.php +@@ -24,4 +24,9 @@ trait HandlesHtmlAttributeForwarding + fn ($value) => is_scalar($value) || is_null($value) || $value instanceof Htmlable + ); + } ++ ++ public function getNonHtmlAttributes(): array ++ { ++ return array_diff_key($this->htmlAttributes, $this->getHtmlAttributes()); ++ } + } +diff --git a/src/Features/SupportHtmlAttributeForwarding/SupportHtmlAttributeForwarding.php b/src/Features/SupportHtmlAttributeForwarding/SupportHtmlAttributeForwarding.php +index 9279e324..e50b028a 100644 +--- a/src/Features/SupportHtmlAttributeForwarding/SupportHtmlAttributeForwarding.php ++++ b/src/Features/SupportHtmlAttributeForwarding/SupportHtmlAttributeForwarding.php +@@ -9,23 +9,17 @@ class SupportHtmlAttributeForwarding extends ComponentHook + { + public function render($view, $properties) + { +- $attributes = $this->component->getHtmlAttributes(); +- +- $view->with(['attributes' => new ComponentAttributeBag($attributes)]); ++ $this->forwardAttributesToView($view); + } + + public function renderIsland($name, $view, $properties) + { +- $attributes = $this->component->getHtmlAttributes(); +- +- $view->with(['attributes' => new ComponentAttributeBag($attributes)]); ++ $this->forwardAttributesToView($view); + } + + public function renderPlaceholder($view, $properties) + { +- $attributes = $this->component->getHtmlAttributes(); +- +- $view->with(['attributes' => new ComponentAttributeBag($attributes)]); ++ $this->forwardAttributesToView($view); + } + + function hydrate($memo) +@@ -45,4 +39,13 @@ class SupportHtmlAttributeForwarding extends ComponentHook + $context->addMemo('attributes', $attributes); + } + } +-} +\ No newline at end of file ++ ++ protected function forwardAttributesToView($view) ++ { ++ $attributes = $this->component->getHtmlAttributes(); ++ ++ $view->with($this->component->getNonHtmlAttributes()); ++ ++ $view->with(['attributes' => new ComponentAttributeBag($attributes)]); ++ } ++} +diff --git a/src/Features/SupportHtmlAttributeForwarding/UnitTest.php b/src/Features/SupportHtmlAttributeForwarding/UnitTest.php +index 507be6cb..3e17a0a4 100644 +--- a/src/Features/SupportHtmlAttributeForwarding/UnitTest.php ++++ b/src/Features/SupportHtmlAttributeForwarding/UnitTest.php +@@ -193,6 +193,89 @@ class UnitTest extends TestCase + $this->assertStringNotContainsString('first@example.com', $html); + $this->assertStringNotContainsString('pageFilters', $html); + } ++ ++ public function test_non_html_attributes_are_available_to_blade_props() ++ { ++ Livewire::component('alert', AlertWithProps::class); ++ ++ $html = Livewire::mount('alert', [ ++ 'rows' => [ ++ ['id' => 1, 'name' => 'Alice'], ++ ['id' => 2, 'name' => 'Bob'], ++ ], ++ 'id' => 'rows-component', ++ ]); ++ ++ $this->assertStringContainsString('Alice', $html); ++ $this->assertStringContainsString('Bob', $html); ++ $this->assertStringContainsString('id="rows-component"', $html); ++ $this->assertStringNotContainsString('rows=', $html); ++ } ++ ++ public function test_non_html_attributes_are_available_as_blade_props_without_default() ++ { ++ Livewire::component('alert', AlertWithPropsWithoutDefault::class); ++ ++ $html = Livewire::mount('alert', [ ++ 'rows' => [ ++ ['id' => 1, 'name' => 'Alice'], ++ ], ++ 'id' => 'rows-component', ++ ]); ++ ++ $this->assertStringContainsString('Alice', $html); ++ $this->assertStringContainsString('id="rows-component"', $html); ++ $this->assertStringNotContainsString('rows=', $html); ++ } ++ ++ public function test_html_attributes_are_forwarded_while_non_html_attributes_are_available_as_blade_props() ++ { ++ Livewire::component('alert', AlertWithProps::class); ++ ++ $html = Livewire::mount('alert', [ ++ 'rows' => [ ++ ['id' => 1, 'name' => 'Alice'], ++ ], ++ 'id' => 'rows-component', ++ ]); ++ ++ $this->assertStringContainsString('Alice', $html); ++ $this->assertStringContainsString('id="rows-component"', $html); ++ $this->assertStringNotContainsString('rows="', $html); ++ } ++ ++ public function test_non_html_attributes_are_available_as_blade_props_in_placeholder() ++ { ++ SupportLazyLoading::$disableWhileTesting = false; ++ ++ Livewire::component('alert', LazyAlertWithProps::class); ++ ++ $html = Livewire::mount('alert', [ ++ 'lazy' => true, ++ 'rows' => [ ++ ['id' => 1, 'name' => 'Alice'], ++ ], ++ 'id' => 'rows-component', ++ ]); ++ ++ $this->assertStringContainsString('Alice', $html); ++ $this->assertStringContainsString('id="rows-component"', $html); ++ $this->assertStringNotContainsString('rows=', $html); ++ } ++ ++ public function test_eloquent_model_are_available_as_blade_props_without_being_dehydrated() ++ { ++ Livewire::component('alert', AlertWithRecordProps::class); ++ ++ $html = Livewire::mount('alert', [ ++ 'record' => RecordModel::first(), ++ 'id' => 'rows-component', ++ ]); ++ ++ $this->assertStringContainsString('First User', $html); ++ $this->assertStringContainsString('id="rows-component"', $html); ++ $this->assertStringNotContainsString('first@example.com', $html); ++ } + } + + class RecordModel extends Model +@@ -239,3 +322,59 @@ class AlertWithIslandAttributes extends Component + HTML; + } + } ++ ++class AlertWithProps extends Component ++{ ++ public function render() ++ { ++ return <<<'HTML' ++ @props(['rows' => []]) ++
    ++ @foreach ($rows as $row) ++
  • {{ $row['name'] }}
  • ++ @endforeach ++
++ HTML; ++ } ++} ++ ++class AlertWithPropsWithoutDefault extends Component ++{ ++ public function render() ++ { ++ return <<<'HTML' ++ @props(['rows']) ++
++ {{ $rows[0]['name'] }} ++
++ HTML; ++ } ++} ++ ++#[Lazy] ++class LazyAlertWithProps extends Component ++{ ++ public function placeholder() ++ { ++ return <<<'HTML' ++ @props(['rows']) ++
{{ $rows[0]['name'] }}
++ HTML; ++ } ++ ++ public function render() ++ { ++ return '
Alert
'; ++ } ++} ++ ++class AlertWithRecordProps extends Component ++{ ++ public function render() ++ { ++ return <<<'HTML' ++ @props(['record']) ++
{{ $record->name }}
++ HTML; ++ } ++} diff --git a/tasks/livewire__livewire-10682/tests/test.sh b/tasks/livewire__livewire-10682/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..a4e6c79f51aa050a73015d82c6010df426d332e3 --- /dev/null +++ b/tasks/livewire__livewire-10682/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 76c76760242aa690abd0db451cd7a32b4c360adb > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/livewire__livewire-10682/tests/verifier.py b/tasks/livewire__livewire-10682/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/livewire__livewire-10682/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/livewire__livewire-10687/environment/Dockerfile b/tasks/livewire__livewire-10687/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..5c3fbc3e979838bc1a19188d99521cd5a683dd94 --- /dev/null +++ b/tasks/livewire__livewire-10687/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/livewire/livewire.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/livewire/livewire.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/livewire/livewire.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 48d4e1bbf7fcf245e672ea67a025dfc5412ae8db 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 48d4e1bbf7fcf245e672ea67a025dfc5412ae8db \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 48d4e1bbf7fcf245e672ea67a025dfc5412ae8db \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/livewire__livewire-10687/instruction.md b/tasks/livewire__livewire-10687/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c16d9b48c7c736db463f388ef59671da6b89229a --- /dev/null +++ b/tasks/livewire__livewire-10687/instruction.md @@ -0,0 +1,15 @@ +# Issue + +**Title:** [4.x] Don't read uninitialized typed properties when expanding consolidated form object updates + +## Description + +A component with a typed public property that is never assigned dehydrates as `null`, so the property is still uninitialized on the next request. `expandConsolidatedFormObjectUpdates()` guards its `instanceof Form` read with `property_exists()`, which is true for a declared-but-uninitialized typed property, and the read itself throws. + +That happens before `updateProperty()`, so no `update` hooks run and `#[Locked]` never gets a chance to throw. A tampered update on a locked property comes back as a 500 instead of the 419 the lock is meant to produce. + +The pre-pass now skips properties that hold no value, using the same `Utils::propertyIsTypedAndUninitialized()` check `FormObjectSynth` already relies on. The update falls through to `updateProperty()` and the lock behaves as expected. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `48d4e1bbf7fc`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10687/solution/patch.diff b/tasks/livewire__livewire-10687/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..b0b60ede02d16ca7d8cafc7040db6b1f7b8c546e --- /dev/null +++ b/tasks/livewire__livewire-10687/solution/patch.diff @@ -0,0 +1,42 @@ +diff --git a/src/Features/SupportLockedProperties/UnitTest.php b/src/Features/SupportLockedProperties/UnitTest.php +index c4d213b0..d29569c0 100644 +--- a/src/Features/SupportLockedProperties/UnitTest.php ++++ b/src/Features/SupportLockedProperties/UnitTest.php +@@ -43,6 +43,20 @@ class UnitTest extends \Tests\TestCase + ->set('foo.count', 2); + } + ++ function test_cant_update_uninitialized_typed_locked_property_with_an_array() ++ { ++ $this->expectException(CannotUpdateLockedPropertyException::class); ++ $this->expectExceptionMessage( ++ 'Cannot update locked property: [group]' ++ ); ++ ++ Livewire::test(new class extends TestComponent { ++ #[BaseLocked] ++ public \stdClass $group; ++ }) ++ ->set('group', ['count' => 1]); ++ } ++ + function test_can_update_locked_property_with_similar_name() + { + Livewire::test(new class extends TestComponent { +diff --git a/src/Mechanisms/HandleComponents/HandleComponents.php b/src/Mechanisms/HandleComponents/HandleComponents.php +index 69189f08..1e274ac3 100644 +--- a/src/Mechanisms/HandleComponents/HandleComponents.php ++++ b/src/Mechanisms/HandleComponents/HandleComponents.php +@@ -416,7 +416,11 @@ class HandleComponents extends Mechanism + $expanded = []; + + foreach ($updates as $path => $value) { +- if (is_array($value) && property_exists($component, $path) && $component->$path instanceof Form) { ++ if (is_array($value) ++ && property_exists($component, $path) ++ && ! Utils::propertyIsTypedAndUninitialized($component, $path) ++ && $component->$path instanceof Form ++ ) { + foreach ($value as $key => $child) { + $expanded["{$path}.{$key}"] = $child; + } diff --git a/tasks/livewire__livewire-10687/solution/solve.sh b/tasks/livewire__livewire-10687/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/livewire__livewire-10687/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/livewire__livewire-10687/task.toml b/tasks/livewire__livewire-10687/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..5cf76d2f9fd7033e70b38ba9bd438cf5f3a0a5b0 --- /dev/null +++ b/tasks/livewire__livewire-10687/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/livewire__livewire-10687" +description = "[4.x] Don't read uninitialized typed properties when expanding consolidated form object updates" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "livewire", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "livewire/livewire" +ref = "48d4e1bbf7fcf245e672ea67a025dfc5412ae8db" +reference = "https://github.com/livewire/livewire/pull/10687" +source_access = "auto" +built_at = "2026-11-16T16:09:51.499151+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:c9061b24a7a1658ed256212450850e962e45cdf992134b92d6763976da22d6f2" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-09T12:48:13Z" +diff_format = "unified" +context_files = [ + "src/Features/SupportLockedProperties/UnitTest.php", + "src/Mechanisms/HandleComponents/HandleComponents.php", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 20 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.410366+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:2691dac89dfd951d3d51f83029cbccefae4ae37fddf7d6e10ac35132b750426c" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/livewire__livewire-10687/tests/capture.py b/tasks/livewire__livewire-10687/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/livewire__livewire-10687/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/livewire__livewire-10687/tests/instruction.md b/tasks/livewire__livewire-10687/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c16d9b48c7c736db463f388ef59671da6b89229a --- /dev/null +++ b/tasks/livewire__livewire-10687/tests/instruction.md @@ -0,0 +1,15 @@ +# Issue + +**Title:** [4.x] Don't read uninitialized typed properties when expanding consolidated form object updates + +## Description + +A component with a typed public property that is never assigned dehydrates as `null`, so the property is still uninitialized on the next request. `expandConsolidatedFormObjectUpdates()` guards its `instanceof Form` read with `property_exists()`, which is true for a declared-but-uninitialized typed property, and the read itself throws. + +That happens before `updateProperty()`, so no `update` hooks run and `#[Locked]` never gets a chance to throw. A tampered update on a locked property comes back as a 500 instead of the 419 the lock is meant to produce. + +The pre-pass now skips properties that hold no value, using the same `Utils::propertyIsTypedAndUninitialized()` check `FormObjectSynth` already relies on. The update falls through to `updateProperty()` and the lock behaves as expected. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `48d4e1bbf7fc`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10687/tests/oracle.patch b/tasks/livewire__livewire-10687/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..b0b60ede02d16ca7d8cafc7040db6b1f7b8c546e --- /dev/null +++ b/tasks/livewire__livewire-10687/tests/oracle.patch @@ -0,0 +1,42 @@ +diff --git a/src/Features/SupportLockedProperties/UnitTest.php b/src/Features/SupportLockedProperties/UnitTest.php +index c4d213b0..d29569c0 100644 +--- a/src/Features/SupportLockedProperties/UnitTest.php ++++ b/src/Features/SupportLockedProperties/UnitTest.php +@@ -43,6 +43,20 @@ class UnitTest extends \Tests\TestCase + ->set('foo.count', 2); + } + ++ function test_cant_update_uninitialized_typed_locked_property_with_an_array() ++ { ++ $this->expectException(CannotUpdateLockedPropertyException::class); ++ $this->expectExceptionMessage( ++ 'Cannot update locked property: [group]' ++ ); ++ ++ Livewire::test(new class extends TestComponent { ++ #[BaseLocked] ++ public \stdClass $group; ++ }) ++ ->set('group', ['count' => 1]); ++ } ++ + function test_can_update_locked_property_with_similar_name() + { + Livewire::test(new class extends TestComponent { +diff --git a/src/Mechanisms/HandleComponents/HandleComponents.php b/src/Mechanisms/HandleComponents/HandleComponents.php +index 69189f08..1e274ac3 100644 +--- a/src/Mechanisms/HandleComponents/HandleComponents.php ++++ b/src/Mechanisms/HandleComponents/HandleComponents.php +@@ -416,7 +416,11 @@ class HandleComponents extends Mechanism + $expanded = []; + + foreach ($updates as $path => $value) { +- if (is_array($value) && property_exists($component, $path) && $component->$path instanceof Form) { ++ if (is_array($value) ++ && property_exists($component, $path) ++ && ! Utils::propertyIsTypedAndUninitialized($component, $path) ++ && $component->$path instanceof Form ++ ) { + foreach ($value as $key => $child) { + $expanded["{$path}.{$key}"] = $child; + } diff --git a/tasks/livewire__livewire-10687/tests/test.sh b/tasks/livewire__livewire-10687/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..f027ef62db9fc1be2b1ecbca4f3f3e800aa56523 --- /dev/null +++ b/tasks/livewire__livewire-10687/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 48d4e1bbf7fcf245e672ea67a025dfc5412ae8db > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/livewire__livewire-10687/tests/verifier.py b/tasks/livewire__livewire-10687/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/livewire__livewire-10687/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/livewire__livewire-10690/environment/Dockerfile b/tasks/livewire__livewire-10690/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..5c3fbc3e979838bc1a19188d99521cd5a683dd94 --- /dev/null +++ b/tasks/livewire__livewire-10690/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/livewire/livewire.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/livewire/livewire.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/livewire/livewire.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 48d4e1bbf7fcf245e672ea67a025dfc5412ae8db 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 48d4e1bbf7fcf245e672ea67a025dfc5412ae8db \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 48d4e1bbf7fcf245e672ea67a025dfc5412ae8db \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/livewire__livewire-10690/instruction.md b/tasks/livewire__livewire-10690/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c6b2d9a240ce50eabe2c770b1476567debb5fe86 --- /dev/null +++ b/tasks/livewire__livewire-10690/instruction.md @@ -0,0 +1,43 @@ +# Issue + +**Title:** [4.x] Only report missing component methods in debug mode + +## Description + +> [!NOTE] +> This is an alternative from but from exception handler. Also This PR doesnt take lazy component path. + +## Summary + +This PR prevents Livewire from reporting errors caused by requests for component methods that do not exist when the application is not running in debug mode. + +Previously, when Livewire received a request targeting a missing component method—such as a scanner, bot, probe, or other automated request attempting to invoke arbitrary methods—the resulting exception could be reported even though it was caused by an invalid external request rather than an application error. + +This can generate unnecessary noise in production error reporting and monitoring services. + +This change limits reporting of these "method not found" errors to debug mode. In production, the invalid request continues to be handled appropriately, but the exception is no longer reported as an application error. + +## Trade-off + +This mirrors `CorruptComponentPayloadException`: in production, **all** `MethodNotFoundException`s become a quiet 419 and are not reported—not only scanner tokens like `"|"`. + +**Upside** +- Stops scanner/fuzz noise (`method: "|"`, etc.) from filling error trackers as 500s +- Avoids leaking method names in production responses +- Same posture as other Livewire “invalid payload” paths + +**Downside** +- Legitimate missing methods in production (typos, renames, stale tabs calling old actions) also become generic 419s with no tracker event +- Harder to diagnose production-only “action not found” issues; they look like session/page-expired rather than a missing method + +**Mitigation** +- Debug (`app.debug = true`) still throws the full `MethodNotFoundException` with the method name +- Missing actions remain obvious during local/staging development + +If we later need production visibility for real missing methods without reintroducing scanner noise, we can narrow quieting to implausible method tokens only (e.g. non-PHP-identifiers) and keep reportable 500s for names like `missingAction`. + +Possibility fixes: + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `48d4e1bbf7fc`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10690/solution/patch.diff b/tasks/livewire__livewire-10690/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..dd58e047c31c2911f961bc1361dd6c3a83d77d2b --- /dev/null +++ b/tasks/livewire__livewire-10690/solution/patch.diff @@ -0,0 +1,113 @@ +diff --git a/src/Exceptions/MethodNotFoundException.php b/src/Exceptions/MethodNotFoundException.php +index 964ff8fe..2bd2abc2 100644 +--- a/src/Exceptions/MethodNotFoundException.php ++++ b/src/Exceptions/MethodNotFoundException.php +@@ -12,4 +12,18 @@ class MethodNotFoundException extends \Exception + "Unable to call component method. Public method [{$method}] not found on component" + ); + } ++ ++ public function report(): bool ++ { ++ return ! config('app.debug'); ++ } ++ ++ // In debug mode, let Laravel render the full error page. ++ // In production, return a generic 419 to avoid leaking details. ++ public function render($request) ++ { ++ if (config('app.debug')) return false; ++ ++ return response('', 419); ++ } + } +diff --git a/src/Mechanisms/HandleComponents/UnitTest.php b/src/Mechanisms/HandleComponents/UnitTest.php +index 456c0a66..e82bce6f 100644 +--- a/src/Mechanisms/HandleComponents/UnitTest.php ++++ b/src/Mechanisms/HandleComponents/UnitTest.php +@@ -2,12 +2,15 @@ + + namespace Livewire\Mechanisms\HandleComponents; + ++use Illuminate\Contracts\Debug\ExceptionHandler; + use Illuminate\Support\Carbon; + use Illuminate\Support\Facades\Route; + use Illuminate\Support\Stringable; + use Livewire\Component; ++use Livewire\Exceptions\MethodNotFoundException; + use Livewire\Form; + use Livewire\Livewire; ++use Livewire\Mechanisms\HandleRequests\EndpointResolver; + use Tests\TestComponent; + + class UnitTest extends \Tests\TestCase +@@ -267,6 +270,69 @@ class UnitTest extends \Tests\TestCase + ->call('refresh') + ->assertSetStrict('refreshed', true); + } ++ ++ public function test_invalid_call_method_name_returns_419_when_debug_is_disabled() ++ { ++ config()->set('app.debug', false); ++ ++ $component = Livewire::test(TestComponent::class); ++ ++ $response = $this->withHeaders(['X-Livewire' => 'true']) ++ ->postJson(EndpointResolver::updatePath(), ['components' => [ ++ [ ++ 'snapshot' => json_encode($component->snapshot), ++ 'updates' => [], ++ 'calls' => [ ++ ['method' => '|', 'params' => [], 'metadata' => []], ++ ], ++ ], ++ ]]); ++ ++ $response->assertStatus(419); ++ } ++ ++ public function test_method_not_found_exception_is_not_reported_when_debug_is_disabled() ++ { ++ config()->set('app.debug', false); ++ ++ $reported = []; ++ app(ExceptionHandler::class) ++ ->reportable(function (MethodNotFoundException $e) use (&$reported) { ++ $reported[] = $e; ++ ++ return false; ++ }); ++ ++ app(ExceptionHandler::class)->report(new MethodNotFoundException('invalidAction')); ++ ++ $this->assertEmpty($reported); ++ } ++ ++ public function test_invalid_call_method_name_throws_method_not_found_when_debug_is_enabled() ++ { ++ config()->set('app.debug', true); ++ ++ $this->expectException(MethodNotFoundException::class); ++ ++ Livewire::test(TestComponent::class)->call('missingAction'); ++ } ++ ++ public function test_method_not_found_exception_is_reported_when_debug_is_enabled() ++ { ++ config()->set('app.debug', true); ++ ++ $reported = []; ++ app(ExceptionHandler::class) ++ ->reportable(function (MethodNotFoundException $e) use (&$reported) { ++ $reported[] = $e; ++ ++ return false; ++ }); ++ ++ app(ExceptionHandler::class)->report(new MethodNotFoundException('invalidAction')); ++ ++ $this->assertCount(1, $reported); ++ } + } + + class BasicComponent extends TestComponent diff --git a/tasks/livewire__livewire-10690/solution/solve.sh b/tasks/livewire__livewire-10690/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/livewire__livewire-10690/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/livewire__livewire-10690/task.toml b/tasks/livewire__livewire-10690/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..371ef5ab802ce6d0a48b0fc7cc40f0b2aaca9f68 --- /dev/null +++ b/tasks/livewire__livewire-10690/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/livewire__livewire-10690" +description = "[4.x] Only report missing component methods in debug mode" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "livewire", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "livewire/livewire" +ref = "48d4e1bbf7fcf245e672ea67a025dfc5412ae8db" +reference = "https://github.com/livewire/livewire/pull/10690" +source_access = "auto" +built_at = "2026-11-16T16:09:51.457353+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:7d2e381c1770ecc73bcdecb2ad717c61b57de4e2572b504d82d1fa40517a80a8" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-21T13:09:05Z" +diff_format = "unified" +context_files = [ + "src/Exceptions/MethodNotFoundException.php", + "src/Mechanisms/HandleComponents/UnitTest.php", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 80 +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.410900+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:2691dac89dfd951d3d51f83029cbccefae4ae37fddf7d6e10ac35132b750426c" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/livewire__livewire-10690/tests/capture.py b/tasks/livewire__livewire-10690/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/livewire__livewire-10690/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/livewire__livewire-10690/tests/instruction.md b/tasks/livewire__livewire-10690/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c6b2d9a240ce50eabe2c770b1476567debb5fe86 --- /dev/null +++ b/tasks/livewire__livewire-10690/tests/instruction.md @@ -0,0 +1,43 @@ +# Issue + +**Title:** [4.x] Only report missing component methods in debug mode + +## Description + +> [!NOTE] +> This is an alternative from but from exception handler. Also This PR doesnt take lazy component path. + +## Summary + +This PR prevents Livewire from reporting errors caused by requests for component methods that do not exist when the application is not running in debug mode. + +Previously, when Livewire received a request targeting a missing component method—such as a scanner, bot, probe, or other automated request attempting to invoke arbitrary methods—the resulting exception could be reported even though it was caused by an invalid external request rather than an application error. + +This can generate unnecessary noise in production error reporting and monitoring services. + +This change limits reporting of these "method not found" errors to debug mode. In production, the invalid request continues to be handled appropriately, but the exception is no longer reported as an application error. + +## Trade-off + +This mirrors `CorruptComponentPayloadException`: in production, **all** `MethodNotFoundException`s become a quiet 419 and are not reported—not only scanner tokens like `"|"`. + +**Upside** +- Stops scanner/fuzz noise (`method: "|"`, etc.) from filling error trackers as 500s +- Avoids leaking method names in production responses +- Same posture as other Livewire “invalid payload” paths + +**Downside** +- Legitimate missing methods in production (typos, renames, stale tabs calling old actions) also become generic 419s with no tracker event +- Harder to diagnose production-only “action not found” issues; they look like session/page-expired rather than a missing method + +**Mitigation** +- Debug (`app.debug = true`) still throws the full `MethodNotFoundException` with the method name +- Missing actions remain obvious during local/staging development + +If we later need production visibility for real missing methods without reintroducing scanner noise, we can narrow quieting to implausible method tokens only (e.g. non-PHP-identifiers) and keep reportable 500s for names like `missingAction`. + +Possibility fixes: + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `48d4e1bbf7fc`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10690/tests/oracle.patch b/tasks/livewire__livewire-10690/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..dd58e047c31c2911f961bc1361dd6c3a83d77d2b --- /dev/null +++ b/tasks/livewire__livewire-10690/tests/oracle.patch @@ -0,0 +1,113 @@ +diff --git a/src/Exceptions/MethodNotFoundException.php b/src/Exceptions/MethodNotFoundException.php +index 964ff8fe..2bd2abc2 100644 +--- a/src/Exceptions/MethodNotFoundException.php ++++ b/src/Exceptions/MethodNotFoundException.php +@@ -12,4 +12,18 @@ class MethodNotFoundException extends \Exception + "Unable to call component method. Public method [{$method}] not found on component" + ); + } ++ ++ public function report(): bool ++ { ++ return ! config('app.debug'); ++ } ++ ++ // In debug mode, let Laravel render the full error page. ++ // In production, return a generic 419 to avoid leaking details. ++ public function render($request) ++ { ++ if (config('app.debug')) return false; ++ ++ return response('', 419); ++ } + } +diff --git a/src/Mechanisms/HandleComponents/UnitTest.php b/src/Mechanisms/HandleComponents/UnitTest.php +index 456c0a66..e82bce6f 100644 +--- a/src/Mechanisms/HandleComponents/UnitTest.php ++++ b/src/Mechanisms/HandleComponents/UnitTest.php +@@ -2,12 +2,15 @@ + + namespace Livewire\Mechanisms\HandleComponents; + ++use Illuminate\Contracts\Debug\ExceptionHandler; + use Illuminate\Support\Carbon; + use Illuminate\Support\Facades\Route; + use Illuminate\Support\Stringable; + use Livewire\Component; ++use Livewire\Exceptions\MethodNotFoundException; + use Livewire\Form; + use Livewire\Livewire; ++use Livewire\Mechanisms\HandleRequests\EndpointResolver; + use Tests\TestComponent; + + class UnitTest extends \Tests\TestCase +@@ -267,6 +270,69 @@ class UnitTest extends \Tests\TestCase + ->call('refresh') + ->assertSetStrict('refreshed', true); + } ++ ++ public function test_invalid_call_method_name_returns_419_when_debug_is_disabled() ++ { ++ config()->set('app.debug', false); ++ ++ $component = Livewire::test(TestComponent::class); ++ ++ $response = $this->withHeaders(['X-Livewire' => 'true']) ++ ->postJson(EndpointResolver::updatePath(), ['components' => [ ++ [ ++ 'snapshot' => json_encode($component->snapshot), ++ 'updates' => [], ++ 'calls' => [ ++ ['method' => '|', 'params' => [], 'metadata' => []], ++ ], ++ ], ++ ]]); ++ ++ $response->assertStatus(419); ++ } ++ ++ public function test_method_not_found_exception_is_not_reported_when_debug_is_disabled() ++ { ++ config()->set('app.debug', false); ++ ++ $reported = []; ++ app(ExceptionHandler::class) ++ ->reportable(function (MethodNotFoundException $e) use (&$reported) { ++ $reported[] = $e; ++ ++ return false; ++ }); ++ ++ app(ExceptionHandler::class)->report(new MethodNotFoundException('invalidAction')); ++ ++ $this->assertEmpty($reported); ++ } ++ ++ public function test_invalid_call_method_name_throws_method_not_found_when_debug_is_enabled() ++ { ++ config()->set('app.debug', true); ++ ++ $this->expectException(MethodNotFoundException::class); ++ ++ Livewire::test(TestComponent::class)->call('missingAction'); ++ } ++ ++ public function test_method_not_found_exception_is_reported_when_debug_is_enabled() ++ { ++ config()->set('app.debug', true); ++ ++ $reported = []; ++ app(ExceptionHandler::class) ++ ->reportable(function (MethodNotFoundException $e) use (&$reported) { ++ $reported[] = $e; ++ ++ return false; ++ }); ++ ++ app(ExceptionHandler::class)->report(new MethodNotFoundException('invalidAction')); ++ ++ $this->assertCount(1, $reported); ++ } + } + + class BasicComponent extends TestComponent diff --git a/tasks/livewire__livewire-10690/tests/test.sh b/tasks/livewire__livewire-10690/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..f027ef62db9fc1be2b1ecbca4f3f3e800aa56523 --- /dev/null +++ b/tasks/livewire__livewire-10690/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 48d4e1bbf7fcf245e672ea67a025dfc5412ae8db > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/livewire__livewire-10690/tests/verifier.py b/tasks/livewire__livewire-10690/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/livewire__livewire-10690/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/livewire__livewire-10692/environment/Dockerfile b/tasks/livewire__livewire-10692/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..9ab2d64c0b39a17e24346f7a7acf5b97e5a8bf33 --- /dev/null +++ b/tasks/livewire__livewire-10692/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/livewire/livewire.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/livewire/livewire.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/livewire/livewire.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 6caabc0014bc8c580e436a9427562dc0696e12df 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 6caabc0014bc8c580e436a9427562dc0696e12df \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 6caabc0014bc8c580e436a9427562dc0696e12df \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/livewire__livewire-10692/instruction.md b/tasks/livewire__livewire-10692/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..dba2a8606e950c305d0fd8b6827abb2265a30962 --- /dev/null +++ b/tasks/livewire__livewire-10692/instruction.md @@ -0,0 +1,20 @@ +# Issue + +**Title:** Fix fragment scrolling after wire:navigate + +## Description + +Navigating with `` updates the URL and replaces the page, but leaves the fragment target below the viewport. This change scrolls the target into view after the existing scroll restoration completes. + +Fragment lookup supports element IDs, percent-encoded IDs, literal percent signs, and legacy named anchors. Missing targets retain the existing scroll-to-top behavior. Cached Back/Forward positions and explicit `preserve-scroll` continue to take precedence. + +Validation: +- Confirmed the new browser regression fails against unmodified `4.x` and passes with the fix. +- Nine focused Dusk browser tests pass with 45 assertions, covering fragment scrolling, missing targets, history restoration, and existing link/programmatic scroll preservation. PHPUnit reports two deprecations. +- Rebuilt JavaScript assets for browser verification; generated bundles are excluded from the commit. + +This branch contains only the fragment-scrolling fix and browser coverage. No separate discussion was created. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `6caabc0014bc`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10692/solution/patch.diff b/tasks/livewire__livewire-10692/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..457437efd4d59a1ad830655b30cb8e9bbe6c333c --- /dev/null +++ b/tasks/livewire__livewire-10692/solution/patch.diff @@ -0,0 +1,133 @@ +diff --git a/js/plugins/navigate/scroll.js b/js/plugins/navigate/scroll.js +index efcc6dd7..c5b6107f 100644 +--- a/js/plugins/navigate/scroll.js ++++ b/js/plugins/navigate/scroll.js +@@ -26,9 +26,34 @@ export function restoreScrollPositionOrScrollToTop() { + + queueMicrotask(() => { + queueMicrotask(() => { // Double microtask here to make sure scrolling restoration is the LAST thing to happen. (Even after Alpine's x-init functions)... ++ let shouldScrollToFragment = ! document.body.hasAttribute('data-scroll-x') ++ + scroll(document.body) + + document.querySelectorAll(['[x-navigate\\:scroll]', '[wire\\:navigate\\:scroll]']).forEach(scroll) ++ ++ if (shouldScrollToFragment) { ++ getFragmentTarget()?.scrollIntoView({ behavior: 'instant' }) ++ } + }) + }) + } ++ ++function getFragmentTarget() { ++ let fragment = window.location.hash.substring(1) ++ ++ if (! fragment) return ++ ++ let target = document.getElementById(fragment) ++ ++ if (target) return target ++ ++ try { ++ fragment = decodeURIComponent(fragment) ++ } catch (e) { ++ // A malformed escape sequence can still be a valid element ID or name. ++ } ++ ++ return document.getElementById(fragment) ++ || Array.from(document.getElementsByName(fragment)).find(el => el.tagName === 'A') ++} +diff --git a/src/Features/SupportNavigate/BrowserTest.php b/src/Features/SupportNavigate/BrowserTest.php +index a6fbb16e..ca43f6bb 100644 +--- a/src/Features/SupportNavigate/BrowserTest.php ++++ b/src/Features/SupportNavigate/BrowserTest.php +@@ -843,6 +843,60 @@ class BrowserTest extends \Tests\BrowserTestCase + }); + } + ++ public function test_navigate_scrolls_to_fragment_targets() ++ { ++ $this->browse(function ($browser) { ++ foreach (['comments', 'comments%3Areplies', '100%', 'legacy-comments'] as $index => $fragment) { ++ $browser ++ ->visit('/first-scroll') ++ ->waitForNavigate()->click('@link.to.fragment.'.$index) ++ ->assertFragmentIs($fragment) ++ ->assertInViewPort('@second-target'); ++ } ++ }); ++ } ++ ++ public function test_navigate_with_an_unknown_fragment_scrolls_to_top() ++ { ++ $this->browse(function ($browser) { ++ $browser ++ ->visit('/first-scroll') ++ ->waitForNavigate()->click('@link.to.fragment.4') ++ ->assertFragmentIs('missing') ++ ->assertScript('window.scrollY', 0); ++ }); ++ } ++ ++ public function test_navigate_fragment_does_not_override_history_scroll_restoration() ++ { ++ $this->browse(function ($browser) { ++ $browser ++ ->visit('/first-scroll') ++ ->waitForNavigate()->click('@link.to.fragment.0') ++ ->assertInViewPort('@second-target'); ++ ++ $browser->script('window.scrollTo(0, 0)'); ++ ++ $browser ++ ->assertScript('window.scrollY', 0) ++ ->waitForNavigate()->back() ++ ->waitForNavigate()->forward() ++ ->assertFragmentIs('comments') ++ ->assertScript('window.scrollY', 0); ++ }); ++ } ++ ++ public function test_navigate_fragment_respects_preserve_scroll() ++ { ++ $this->browse(function ($browser) { ++ $browser ++ ->visit('/first-scroll') ++ ->waitForNavigate()->click('@link.to.fragment.with.preserve.scroll') ++ ->assertFragmentIs('comments') ++ ->assertScript('window.scrollY', 0); ++ }); ++ } ++ + public function test_navigate_scrolls_to_top_and_back_preserves_scroll() + { + $this->browse(function ($browser) { +@@ -2221,6 +2275,14 @@ class FirstScrollPage extends Component +
+
On first
+ ++
++ Preserve scroll ++ ++ @foreach (['comments', 'comments%3Areplies', '100%', 'legacy-comments', 'missing'] as $fragment) ++ Go to fragment ++ @endforeach ++
++ +
spacer
+ +
below the fold
+@@ -2332,7 +2394,12 @@ class SecondScrollPage extends Component + +
spacer
+ +-
below the fold
++
++ Replies ++ Percentage ++ Legacy comments ++ below the fold ++
+ +
spacer
+
diff --git a/tasks/livewire__livewire-10692/solution/solve.sh b/tasks/livewire__livewire-10692/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/livewire__livewire-10692/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/livewire__livewire-10692/task.toml b/tasks/livewire__livewire-10692/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..b3dffd10dc5ae6c6334866bfdac3bdebcdba4827 --- /dev/null +++ b/tasks/livewire__livewire-10692/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/livewire__livewire-10692" +description = "Fix fragment scrolling after wire:navigate" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "livewire", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "livewire/livewire" +ref = "6caabc0014bc8c580e436a9427562dc0696e12df" +reference = "https://github.com/livewire/livewire/pull/10692" +source_access = "auto" +built_at = "2026-11-16T16:09:51.497544+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:f1ec7c0229b179d40ed71ad3670b630092810d5a2fc82b3cfbc610f8529a1579" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-09T14:18:48Z" +diff_format = "unified" +context_files = [ + "js/plugins/navigate/scroll.js", + "src/Features/SupportNavigate/BrowserTest.php", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 94 +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.411401+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:47fb1778dd84d811a664351218e2a6c562031ca4caf29754da44aa4b58cb350b" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/livewire__livewire-10692/tests/capture.py b/tasks/livewire__livewire-10692/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/livewire__livewire-10692/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/livewire__livewire-10692/tests/instruction.md b/tasks/livewire__livewire-10692/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..dba2a8606e950c305d0fd8b6827abb2265a30962 --- /dev/null +++ b/tasks/livewire__livewire-10692/tests/instruction.md @@ -0,0 +1,20 @@ +# Issue + +**Title:** Fix fragment scrolling after wire:navigate + +## Description + +Navigating with `` updates the URL and replaces the page, but leaves the fragment target below the viewport. This change scrolls the target into view after the existing scroll restoration completes. + +Fragment lookup supports element IDs, percent-encoded IDs, literal percent signs, and legacy named anchors. Missing targets retain the existing scroll-to-top behavior. Cached Back/Forward positions and explicit `preserve-scroll` continue to take precedence. + +Validation: +- Confirmed the new browser regression fails against unmodified `4.x` and passes with the fix. +- Nine focused Dusk browser tests pass with 45 assertions, covering fragment scrolling, missing targets, history restoration, and existing link/programmatic scroll preservation. PHPUnit reports two deprecations. +- Rebuilt JavaScript assets for browser verification; generated bundles are excluded from the commit. + +This branch contains only the fragment-scrolling fix and browser coverage. No separate discussion was created. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `6caabc0014bc`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10692/tests/oracle.patch b/tasks/livewire__livewire-10692/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..457437efd4d59a1ad830655b30cb8e9bbe6c333c --- /dev/null +++ b/tasks/livewire__livewire-10692/tests/oracle.patch @@ -0,0 +1,133 @@ +diff --git a/js/plugins/navigate/scroll.js b/js/plugins/navigate/scroll.js +index efcc6dd7..c5b6107f 100644 +--- a/js/plugins/navigate/scroll.js ++++ b/js/plugins/navigate/scroll.js +@@ -26,9 +26,34 @@ export function restoreScrollPositionOrScrollToTop() { + + queueMicrotask(() => { + queueMicrotask(() => { // Double microtask here to make sure scrolling restoration is the LAST thing to happen. (Even after Alpine's x-init functions)... ++ let shouldScrollToFragment = ! document.body.hasAttribute('data-scroll-x') ++ + scroll(document.body) + + document.querySelectorAll(['[x-navigate\\:scroll]', '[wire\\:navigate\\:scroll]']).forEach(scroll) ++ ++ if (shouldScrollToFragment) { ++ getFragmentTarget()?.scrollIntoView({ behavior: 'instant' }) ++ } + }) + }) + } ++ ++function getFragmentTarget() { ++ let fragment = window.location.hash.substring(1) ++ ++ if (! fragment) return ++ ++ let target = document.getElementById(fragment) ++ ++ if (target) return target ++ ++ try { ++ fragment = decodeURIComponent(fragment) ++ } catch (e) { ++ // A malformed escape sequence can still be a valid element ID or name. ++ } ++ ++ return document.getElementById(fragment) ++ || Array.from(document.getElementsByName(fragment)).find(el => el.tagName === 'A') ++} +diff --git a/src/Features/SupportNavigate/BrowserTest.php b/src/Features/SupportNavigate/BrowserTest.php +index a6fbb16e..ca43f6bb 100644 +--- a/src/Features/SupportNavigate/BrowserTest.php ++++ b/src/Features/SupportNavigate/BrowserTest.php +@@ -843,6 +843,60 @@ class BrowserTest extends \Tests\BrowserTestCase + }); + } + ++ public function test_navigate_scrolls_to_fragment_targets() ++ { ++ $this->browse(function ($browser) { ++ foreach (['comments', 'comments%3Areplies', '100%', 'legacy-comments'] as $index => $fragment) { ++ $browser ++ ->visit('/first-scroll') ++ ->waitForNavigate()->click('@link.to.fragment.'.$index) ++ ->assertFragmentIs($fragment) ++ ->assertInViewPort('@second-target'); ++ } ++ }); ++ } ++ ++ public function test_navigate_with_an_unknown_fragment_scrolls_to_top() ++ { ++ $this->browse(function ($browser) { ++ $browser ++ ->visit('/first-scroll') ++ ->waitForNavigate()->click('@link.to.fragment.4') ++ ->assertFragmentIs('missing') ++ ->assertScript('window.scrollY', 0); ++ }); ++ } ++ ++ public function test_navigate_fragment_does_not_override_history_scroll_restoration() ++ { ++ $this->browse(function ($browser) { ++ $browser ++ ->visit('/first-scroll') ++ ->waitForNavigate()->click('@link.to.fragment.0') ++ ->assertInViewPort('@second-target'); ++ ++ $browser->script('window.scrollTo(0, 0)'); ++ ++ $browser ++ ->assertScript('window.scrollY', 0) ++ ->waitForNavigate()->back() ++ ->waitForNavigate()->forward() ++ ->assertFragmentIs('comments') ++ ->assertScript('window.scrollY', 0); ++ }); ++ } ++ ++ public function test_navigate_fragment_respects_preserve_scroll() ++ { ++ $this->browse(function ($browser) { ++ $browser ++ ->visit('/first-scroll') ++ ->waitForNavigate()->click('@link.to.fragment.with.preserve.scroll') ++ ->assertFragmentIs('comments') ++ ->assertScript('window.scrollY', 0); ++ }); ++ } ++ + public function test_navigate_scrolls_to_top_and_back_preserves_scroll() + { + $this->browse(function ($browser) { +@@ -2221,6 +2275,14 @@ class FirstScrollPage extends Component +
+
On first
+ ++
++ Preserve scroll ++ ++ @foreach (['comments', 'comments%3Areplies', '100%', 'legacy-comments', 'missing'] as $fragment) ++ Go to fragment ++ @endforeach ++
++ +
spacer
+ +
below the fold
+@@ -2332,7 +2394,12 @@ class SecondScrollPage extends Component + +
spacer
+ +-
below the fold
++
++ Replies ++ Percentage ++ Legacy comments ++ below the fold ++
+ +
spacer
+
diff --git a/tasks/livewire__livewire-10692/tests/test.sh b/tasks/livewire__livewire-10692/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b0891b9eebd3e55da27da2e23e3c63aab0c4cbe0 --- /dev/null +++ b/tasks/livewire__livewire-10692/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 6caabc0014bc8c580e436a9427562dc0696e12df > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/livewire__livewire-10692/tests/verifier.py b/tasks/livewire__livewire-10692/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/livewire__livewire-10692/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/livewire__livewire-10693/environment/Dockerfile b/tasks/livewire__livewire-10693/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..24eefddb12292b080cb889e01f09b60af40ad335 --- /dev/null +++ b/tasks/livewire__livewire-10693/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/livewire/livewire.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/livewire/livewire.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/livewire/livewire.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 31b12dd0f4b44bfa9a5c2fb3d13dd93ad35dad3f 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 31b12dd0f4b44bfa9a5c2fb3d13dd93ad35dad3f \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 31b12dd0f4b44bfa9a5c2fb3d13dd93ad35dad3f \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/livewire__livewire-10693/instruction.md b/tasks/livewire__livewire-10693/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b1f8c5527f96205daac05b7dc6902dfcfc216031 --- /dev/null +++ b/tasks/livewire__livewire-10693/instruction.md @@ -0,0 +1,25 @@ +# Issue + +**Title:** Avoid fetching and swapping for same-page fragment navigation + +## Description + +Clicking a `wire:navigate` link from `/posts` to `/posts#comments` currently fetches and replaces the page, resetting component state and unsaved input. Same-page fragment visits now update history and scroll while keeping the existing page alive. Hover and press prefetching are skipped too. + +This is a and is based on its branch so the diff contains only the same-page behavior. Merge #10692 first, then retarget this PR to `4.x`. + +The shortcut requires the same origin, path, and query string. Different pages and query strings still use ordinary navigation. Clicking the same fragment again scrolls without adding another history entry; an empty fragment scrolls to the top. Both link and programmatic `preserveScroll` are respected. + +Fragment history entries share a document ID, allowing Back/Forward to preserve live components while the browser restores viewport scrolling. Marked `wire:navigate:scroll` containers restore their saved positions without replacing their DOM. Cross-page history still uses the existing snapshot/fetch path. + +Same-page visits retain the cancellable `livewire:navigate` and completion `livewire:navigated` events. They do not emit the page-swap event `livewire:navigating`. + +Validation: +- Reproduced unwanted hover prefetching before the fix with a failing browser regression. +- 29 focused Dusk browser tests pass with 260 assertions, including 11 new tests for state/input preservation, hover, keyboard and programmatic navigation, repeated/empty fragments, cancellation, scroll preservation, nested scroll containers, query changes, page refresh, and history across other pages. +- Existing navigation lifecycle, snapshot-cache, refresh, error-page history, and fragment-scroll checks pass. PHPUnit reports two deprecations. +- Rebuilt JavaScript assets for browser verification. Generated bundles are excluded from the commit. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `31b12dd0f4b4`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10693/solution/patch.diff b/tasks/livewire__livewire-10693/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..554be66006cb3afd205c8e737766d850dd091074 --- /dev/null +++ b/tasks/livewire__livewire-10693/solution/patch.diff @@ -0,0 +1,502 @@ +diff --git a/js/plugins/navigate/history.js b/js/plugins/navigate/history.js +index 030bc3a1..12ca01ff 100644 +--- a/js/plugins/navigate/history.js ++++ b/js/plugins/navigate/history.js +@@ -9,6 +9,7 @@ class Snapshot { + + let snapshotCache = { + currentKey: null, ++ currentDocumentId: Math.random(), + currentUrl: null, + keys: [], + lookup: {}, +@@ -81,7 +82,8 @@ export function updateCurrentPageHtmlInSnapshotCacheForLaterBackButtonClicks(key + + export function whenTheBackOrForwardButtonIsClicked( + registerFallback, +- handleHtml ++ handleHtml, ++ handleFragment + ) { + let fallback + +@@ -103,6 +105,19 @@ export function whenTheBackOrForwardButtonIsClicked( + + if (! alpine.snapshotIdx) return + ++ // Fragment entries belong to the same live page. Let the browser restore ++ // their scroll position without reconstructing the page from a snapshot. ++ if (alpine.documentId && alpine.documentId === snapshotCache.currentDocumentId) { ++ let snapshot = snapshotCache.has(alpine.snapshotIdx) && snapshotCache.retrieve(alpine.snapshotIdx) ++ ++ handleFragment(new URL(window.location.href), snapshot?.html, snapshotCache.currentUrl, snapshotCache.currentKey) ++ ++ snapshotCache.currentKey = alpine.snapshotIdx ++ snapshotCache.currentUrl = new URL(window.location.href) ++ ++ return ++ } ++ + if (snapshotCache.has(alpine.snapshotIdx)) { + let snapshot = snapshotCache.retrieve(alpine.snapshotIdx) + +@@ -110,9 +125,11 @@ export function whenTheBackOrForwardButtonIsClicked( + + snapshotCache.currentKey = alpine.snapshotIdx + snapshotCache.currentUrl = snapshot.url ++ snapshotCache.currentDocumentId = alpine.documentId ?? Math.random() + } else { + snapshotCache.currentKey = null + snapshotCache.currentUrl = null ++ snapshotCache.currentDocumentId = alpine.documentId ?? Math.random() + + fallback(alpine.url) + } +@@ -126,15 +143,17 @@ export function updateUrlAndStoreLatestHtmlForFutureBackButtons( + pushUrl(destination, html) + } + +-export function pushUrl(url, html) { +- updateUrl('pushState', url, html) ++export function pushUrl(url, html, { sameDocument = false } = {}) { ++ updateUrl('pushState', url, html, { sameDocument }) + } + + export function replaceUrl(url, html) { + updateUrl('replaceState', url, html) + } + +-function updateUrl(method, url, html) { ++function updateUrl(method, url, html, { sameDocument = false } = {}) { ++ if (method === 'pushState' && ! sameDocument) snapshotCache.currentDocumentId = Math.random() ++ + let key = url.toString() + '-' + Math.random() + + method === 'pushState' +@@ -150,7 +169,7 @@ function updateUrl(method, url, html) { + } + }) + +- historyCoordinator[method](url, { snapshotIdx: key, url: url.toString() }) ++ historyCoordinator[method](url, { snapshotIdx: key, url: url.toString(), documentId: snapshotCache.currentDocumentId }) + + snapshotCache.currentKey = key + snapshotCache.currentUrl = url +diff --git a/js/plugins/navigate/index.js b/js/plugins/navigate/index.js +index d89dd486..7ed9cfd5 100644 +--- a/js/plugins/navigate/index.js ++++ b/js/plugins/navigate/index.js +@@ -1,6 +1,6 @@ +-import { replaceUrl, updateCurrentPageHtmlInHistoryStateForLaterBackButtonClicks, updateCurrentPageHtmlInSnapshotCacheForLaterBackButtonClicks, updateUrlAndStoreLatestHtmlForFutureBackButtons, whenTheBackOrForwardButtonIsClicked } from "./history" ++import { pushUrl, replaceUrl, updateCurrentPageHtmlInHistoryStateForLaterBackButtonClicks, updateCurrentPageHtmlInSnapshotCacheForLaterBackButtonClicks, updateUrlAndStoreLatestHtmlForFutureBackButtons, whenTheBackOrForwardButtonIsClicked } from "./history" + import { getPretchedHtmlOr, prefetchHtml, storeThePrefetchedHtmlForWhenALinkIsClicked } from "./prefetch" +-import { createUrlObjectFromString, extractDestinationFromLink, isSameOrigin, linkShouldBeHandledNatively, visitNatively, whenThisLinkIsHoveredFor, whenThisLinkIsPressed } from "./links" ++import { createUrlObjectFromString, extractDestinationFromLink, isSameOrigin, isSamePageFragment, linkShouldBeHandledNatively, visitNatively, whenThisLinkIsHoveredFor, whenThisLinkIsPressed } from "./links" + import { isTeleportTarget, packUpPersistedTeleports, removeAnyLeftOverStaleTeleportTargets, unPackPersistedTeleports } from "./teleport" + import { restoreScrollPositionOrScrollToTop, storeScrollInformationInHtmlBeforeNavigatingAway } from "./scroll" + import { isPersistedElement, putPersistantElementsBack, storePersistantElementsForLater } from "./persist" +@@ -50,7 +50,7 @@ export default function (Alpine) { + shouldPrefetchOnHover && whenThisLinkIsHoveredFor(el, 60, () => { + let destination = extractDestinationFromLink(el) + +- if (linkShouldBeHandledNatively(el, destination)) return ++ if (linkShouldBeHandledNatively(el, destination) || isSamePageFragment(destination)) return + + prefetchHtml(destination, (html, finalDestination) => { + storeThePrefetchedHtmlForWhenALinkIsClicked(html, destination, finalDestination) +@@ -62,7 +62,7 @@ export default function (Alpine) { + whenThisLinkIsPressed(el, (whenItIsReleased) => { + let destination = extractDestinationFromLink(el) + +- prefetchHtml(destination, (html, finalDestination) => { ++ if (! isSamePageFragment(destination)) prefetchHtml(destination, (html, finalDestination) => { + storeThePrefetchedHtmlForWhenALinkIsClicked(html, destination, finalDestination) + }, () => { + showProgressBar && finishAndHideProgressBar() +@@ -83,6 +83,24 @@ export default function (Alpine) { + function navigateTo(destination, { preserveScroll = false, shouldPushToHistoryState = true }) { + let navigation = startNavigation() + ++ if (shouldPushToHistoryState && isSamePageFragment(destination)) { ++ navigation.ready() ++ ++ storeScrollInformationInHtmlBeforeNavigatingAway() ++ updateCurrentPageHtmlInHistoryStateForLaterBackButtonClicks() ++ ++ if (destination.href !== window.location.href) { ++ pushUrl(destination, document.documentElement.outerHTML, { sameDocument: true }) ++ } ++ ++ restoreScrollPositionOrScrollToTop({ scrollToFragment: ! preserveScroll }) ++ ++ fireEventForOtherLibrariesToHookInto('alpine:navigated') ++ navigation.finish() ++ ++ return ++ } ++ + showProgressBar && showAndStartProgressBar() + + fetchHtmlOrUsePrefetchedHtml(destination, (html, finalDestination) => { +@@ -251,6 +269,19 @@ export default function (Alpine) { + }) + }) + }, ++ (destination, snapshotHtml, currentPageUrl, currentPageKey) => { ++ let prevented = fireEventForOtherLibrariesToHookInto('alpine:navigate', { ++ url: destination, history: true, cached: true, ++ }) ++ ++ if (prevented) return ++ ++ storeScrollInformationInHtmlBeforeNavigatingAway() ++ updateCurrentPageHtmlInSnapshotCacheForLaterBackButtonClicks(currentPageKey, currentPageUrl) ++ restoreScrollPositionOrScrollToTop({ snapshotHtml }) ++ ++ fireEventForOtherLibrariesToHookInto('alpine:navigated') ++ }, + ) + + // Because DOMContentLoaded is fired on first load, +diff --git a/js/plugins/navigate/links.js b/js/plugins/navigate/links.js +index 1722c566..7048ade6 100644 +--- a/js/plugins/navigate/links.js ++++ b/js/plugins/navigate/links.js +@@ -87,6 +87,13 @@ export function isSameOrigin(destination) { + return !! destination && destination.origin === window.location.origin + } + ++export function isSamePageFragment(destination) { ++ return isSameOrigin(destination) ++ && destination.pathname === window.location.pathname ++ && destination.search === window.location.search ++ && destination.href.includes('#') ++} ++ + export function visitNatively(destination) { + window.location.href = destination.href + } +diff --git a/js/plugins/navigate/scroll.js b/js/plugins/navigate/scroll.js +index c5b6107f..bd529dab 100644 +--- a/js/plugins/navigate/scroll.js ++++ b/js/plugins/navigate/scroll.js +@@ -4,19 +4,30 @@ export function storeScrollInformationInHtmlBeforeNavigatingAway() { + document.body.setAttribute('data-scroll-y', document.body.scrollTop) + + document.querySelectorAll(['[x-navigate\\:scroll]', '[wire\\:navigate\\:scroll]']).forEach(el => { ++ // Match saved scroll positions to live containers during fragment history visits. ++ if (! el.hasAttribute('data-scroll-id')) el.setAttribute('data-scroll-id', Math.random()) ++ + el.setAttribute('data-scroll-x', el.scrollLeft) + el.setAttribute('data-scroll-y', el.scrollTop) + }) + } + +-export function restoreScrollPositionOrScrollToTop() { ++export function restoreScrollPositionOrScrollToTop({ scrollToFragment = false, snapshotHtml = null } = {}) { ++ let savedElements = snapshotHtml ++ ? new DOMParser().parseFromString(snapshotHtml, 'text/html').querySelectorAll('[data-scroll-id]') ++ : [] ++ ++ let savedScroll = new Map(Array.from(savedElements, el => [el.getAttribute('data-scroll-id'), el])) ++ + let scroll = el => { +- if (! el.hasAttribute('data-scroll-x')) { ++ let source = savedScroll.get(el.getAttribute('data-scroll-id')) || el ++ ++ if (! source.hasAttribute('data-scroll-x')) { + window.scrollTo({ top: 0, left: 0, behavior: 'instant' }) + } else { + el.scrollTo({ +- top: Number(el.getAttribute('data-scroll-y')), +- left: Number(el.getAttribute('data-scroll-x')), ++ top: Number(source.getAttribute('data-scroll-y')), ++ left: Number(source.getAttribute('data-scroll-x')), + behavior: 'instant', + }) + el.removeAttribute('data-scroll-x') +@@ -32,7 +43,9 @@ export function restoreScrollPositionOrScrollToTop() { + + document.querySelectorAll(['[x-navigate\\:scroll]', '[wire\\:navigate\\:scroll]']).forEach(scroll) + +- if (shouldScrollToFragment) { ++ if (scrollToFragment && ! window.location.hash) { ++ window.scrollTo({ top: 0, left: 0, behavior: 'instant' }) ++ } else if (shouldScrollToFragment || scrollToFragment) { + getFragmentTarget()?.scrollIntoView({ behavior: 'instant' }) + } + }) +diff --git a/src/Features/SupportNavigate/FragmentBrowserTest.php b/src/Features/SupportNavigate/FragmentBrowserTest.php +new file mode 100644 +index 00000000..06962c97 +--- /dev/null ++++ b/src/Features/SupportNavigate/FragmentBrowserTest.php +@@ -0,0 +1,268 @@ ++middleware('web'); ++ Route::get('/fragment-other', FragmentPage::class)->middleware('web'); ++ }; ++ } ++ ++ public function test_same_page_fragment_links_do_not_fetch_or_swap_the_page() ++ { ++ $this->browse(function ($browser) { ++ $browser->visit('/fragment')->click('@increment')->type('@draft', 'Unsaved draft'); ++ $browser->script('window.fragmentRequests = 0; Livewire.hook("navigate.request", () => window.fragmentRequests++)'); ++ ++ $browser ++ ->waitForNoNavigatePrefetchRequest()->mouseover('@comments') ++ ->waitForNavigate()->click('@comments') ++ ->assertFragmentIs('comments') ++ ->assertInViewPort('@comments-target') ++ ->assertSeeIn('@count', '1') ++ ->assertInputValue('@draft', 'Unsaved draft') ++ ->assertScript('window.fragmentRequests', 0) ++ ->assertConsoleLogHasNoErrors(); ++ }); ++ } ++ ++ public function test_fragment_history_keeps_the_live_page_and_restores_scroll() ++ { ++ $this->browse(function ($browser) { ++ $browser->visit('/fragment')->click('@increment'); ++ $browser->script('window.fragmentRequests = 0; Livewire.hook("navigate.request", () => window.fragmentRequests++)'); ++ ++ $browser ++ ->waitForNavigate()->click('@comments') ++ ->assertInViewPort('@comments-target') ++ ->waitForNavigate()->click('@replies') ++ ->assertInViewPort('@replies-target') ++ ->waitForNavigate()->back() ++ ->assertFragmentIs('comments') ++ ->assertInViewPort('@comments-target') ++ ->assertSeeIn('@count', '1') ++ ->waitForNavigate()->back() ++ ->assertFragmentIs('') ++ ->assertScript('window.scrollY', 0) ++ ->assertSeeIn('@count', '1') ++ ->waitForNavigate()->forward() ++ ->assertFragmentIs('comments') ++ ->assertInViewPort('@comments-target') ++ ->assertSeeIn('@count', '1') ++ ->assertScript('window.fragmentRequests', 0); ++ }); ++ } ++ ++ public function test_fragment_history_works_after_visiting_another_page() ++ { ++ $this->browse(function ($browser) { ++ $browser ++ ->visit('/fragment') ++ ->waitForNavigate()->click('@comments') ++ ->waitForNavigate()->click('@other') ++ ->assertPathIs('/fragment-other') ++ ->waitForNavigate()->back() ++ ->assertPathIs('/fragment') ++ ->assertFragmentIs('comments') ++ ->assertInViewPort('@comments-target') ++ ->click('@increment') ++ ->waitForNavigate()->back() ++ ->assertFragmentIs('') ++ ->assertSeeIn('@count', '1') ++ ->waitForNavigate()->forward() ++ ->assertFragmentIs('comments') ++ ->assertSeeIn('@count', '1') ++ ->waitForNavigate()->forward() ++ ->assertPathIs('/fragment-other'); ++ }); ++ } ++ ++ public function test_programmatic_fragment_navigation_and_preserve_scroll() ++ { ++ $this->browse(function ($browser) { ++ $browser->visit('/fragment')->click('@increment'); ++ $browser->script('window.fragmentRequests = 0; Livewire.hook("navigate.request", () => window.fragmentRequests++)'); ++ ++ $browser ++ ->waitForNavigate()->click('@preserve') ++ ->assertFragmentIs('comments') ++ ->assertScript('window.scrollY', 0) ++ ->waitForNavigate()->click('@programmatic-preserve') ++ ->assertFragmentIs('replies') ++ ->assertScript('window.scrollY', 0) ++ ->waitForNavigate()->click('@programmatic') ++ ->assertFragmentIs('replies') ++ ->assertInViewPort('@replies-target') ++ ->assertSeeIn('@count', '1') ++ ->assertScript('window.fragmentRequests', 0); ++ }); ++ } ++ ++ public function test_fragment_links_support_keyboard_activation_and_repeated_clicks() ++ { ++ $this->browse(function ($browser) { ++ $browser->visit('/fragment')->click('@increment'); ++ $browser->script('window.fragmentRequests = 0; window.fragmentHistoryLength = history.length; Livewire.hook("navigate.request", () => window.fragmentRequests++)'); ++ ++ $browser ++ ->waitForNavigate()->keys('@comments', '{enter}') ++ ->assertFragmentIs('comments') ++ ->assertInViewPort('@comments-target'); ++ ++ $browser->script('window.scrollTo(0, 0)'); ++ ++ $browser ++ ->waitForNavigate()->click('@comments') ++ ->assertInViewPort('@comments-target') ++ ->assertScript('history.length === window.fragmentHistoryLength + 1', true) ++ ->assertSeeIn('@count', '1') ++ ->assertScript('window.fragmentRequests', 0); ++ }); ++ } ++ ++ public function test_empty_fragments_scroll_to_top_without_swapping() ++ { ++ $this->browse(function ($browser) { ++ $browser ++ ->visit('/fragment') ++ ->click('@increment') ++ ->waitForNavigate()->click('@comments') ++ ->assertInViewPort('@comments-target') ++ ->waitForNavigate()->click('@top') ++ ->assertScript('window.scrollY', 0) ++ ->assertSeeIn('@count', '1'); ++ }); ++ } ++ ++ public function test_fragment_navigation_is_cancellable_and_does_not_fire_swap_events() ++ { ++ $this->browse(function ($browser) { ++ $browser->visit('/fragment'); ++ $browser->script(<<<'JS' ++ window.fragmentRequests = 0; ++ window.fragmentSwaps = 0; ++ Livewire.hook('navigate.request', () => window.fragmentRequests++); ++ document.addEventListener('livewire:navigating', () => window.fragmentSwaps++); ++ document.addEventListener('livewire:navigate', event => event.preventDefault(), { once: true }); ++ JS); ++ ++ $browser ++ ->click('@comments') ++ ->assertFragmentIs('') ++ ->assertScript('window.scrollY', 0) ++ ->waitForNavigate()->click('@comments') ++ ->assertFragmentIs('comments') ++ ->assertInViewPort('@comments-target') ++ ->assertScript('window.fragmentRequests', 0) ++ ->assertScript('window.fragmentSwaps', 0); ++ }); ++ } ++ ++ public function test_fragment_history_restores_marked_scroll_containers() ++ { ++ $this->browse(function ($browser) { ++ $browser->visit('/fragment'); ++ $browser->script('document.getElementById("pane").scrollTop = 100'); ++ ++ $browser->waitForNavigate()->click('@comments'); ++ $browser->script('document.getElementById("pane").scrollTop = 200'); ++ ++ $browser ++ ->waitForNavigate()->back() ++ ->assertScript('document.getElementById("pane").scrollTop', 100) ++ ->waitForNavigate()->forward() ++ ->assertScript('document.getElementById("pane").scrollTop', 200); ++ }); ++ } ++ ++ public function test_fragment_history_works_after_a_browser_refresh() ++ { ++ $this->browse(function ($browser) { ++ $browser ++ ->visit('/fragment') ++ ->waitForNavigate()->click('@comments') ++ ->waitForNavigate()->click('@replies') ++ ->refresh() ++ ->waitForNavigate()->back() ++ ->assertFragmentIs('comments') ++ ->assertInViewPort('@comments-target') ++ ->click('@increment') ++ ->waitForNavigate()->back() ++ ->assertFragmentIs('') ++ ->assertSeeIn('@count', '1'); ++ }); ++ } ++ ++ public function test_visiting_the_same_url_without_a_fragment_still_swaps_the_page() ++ { ++ $this->browse(function ($browser) { ++ $browser ++ ->visit('/fragment') ++ ->click('@increment') ++ ->waitForNavigate()->click('@reload') ++ ->assertSeeIn('@count', '0') ++ ->click('@increment') ++ ->click('@increment') ++ ->waitForNavigate()->back() ++ ->assertSeeIn('@count', '0'); ++ }); ++ } ++ ++ public function test_a_query_string_change_still_fetches_and_swaps_the_page() ++ { ++ $this->browse(function ($browser) { ++ $browser->visit('/fragment')->click('@increment'); ++ $browser->script('window.fragmentRequests = 0; Livewire.hook("navigate.request", () => window.fragmentRequests++)'); ++ ++ $browser ++ ->waitForNavigate()->click('@query') ++ ->assertQueryStringHas('page', '2') ++ ->assertFragmentIs('comments') ++ ->assertInViewPort('@comments-target') ++ ->assertSeeIn('@count', '0') ++ ->assertScript('window.fragmentRequests', 1); ++ }); ++ } ++} ++ ++class FragmentPage extends Component ++{ ++ public function render() ++ { ++ return <<<'HTML' ++
++ ++
++
Scrollable pane
++
++
++
Comments
++
++
Replies
++
++
++ HTML; ++ } ++} diff --git a/tasks/livewire__livewire-10693/solution/solve.sh b/tasks/livewire__livewire-10693/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/livewire__livewire-10693/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/livewire__livewire-10693/task.toml b/tasks/livewire__livewire-10693/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..fd45675565895ad8f429a94f58ffade01fb468fc --- /dev/null +++ b/tasks/livewire__livewire-10693/task.toml @@ -0,0 +1,72 @@ +version = "1.0" + +[task] +name = "trending/livewire__livewire-10693" +description = "Avoid fetching and swapping for same-page fragment navigation" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "livewire", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "livewire/livewire" +ref = "31b12dd0f4b44bfa9a5c2fb3d13dd93ad35dad3f" +reference = "https://github.com/livewire/livewire/pull/10693" +source_access = "auto" +built_at = "2026-11-16T16:09:51.487174+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:e9867d78d2609995da56aa3e87766348f1fa5d66bb7ce3ada237526a8bbf8198" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-14T16:33:47Z" +diff_format = "unified" +context_files = [ + "js/plugins/navigate/history.js", + "js/plugins/navigate/index.js", + "js/plugins/navigate/links.js", + "js/plugins/navigate/scroll.js", + "src/Features/SupportNavigate/FragmentBrowserTest.php", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 366 +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.411894+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:9c1576e5274971d0c241399ceaa8921a4456a2f89cfe39c5a5ac1ec7a1ba1762" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/livewire__livewire-10693/tests/capture.py b/tasks/livewire__livewire-10693/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/livewire__livewire-10693/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/livewire__livewire-10693/tests/instruction.md b/tasks/livewire__livewire-10693/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b1f8c5527f96205daac05b7dc6902dfcfc216031 --- /dev/null +++ b/tasks/livewire__livewire-10693/tests/instruction.md @@ -0,0 +1,25 @@ +# Issue + +**Title:** Avoid fetching and swapping for same-page fragment navigation + +## Description + +Clicking a `wire:navigate` link from `/posts` to `/posts#comments` currently fetches and replaces the page, resetting component state and unsaved input. Same-page fragment visits now update history and scroll while keeping the existing page alive. Hover and press prefetching are skipped too. + +This is a and is based on its branch so the diff contains only the same-page behavior. Merge #10692 first, then retarget this PR to `4.x`. + +The shortcut requires the same origin, path, and query string. Different pages and query strings still use ordinary navigation. Clicking the same fragment again scrolls without adding another history entry; an empty fragment scrolls to the top. Both link and programmatic `preserveScroll` are respected. + +Fragment history entries share a document ID, allowing Back/Forward to preserve live components while the browser restores viewport scrolling. Marked `wire:navigate:scroll` containers restore their saved positions without replacing their DOM. Cross-page history still uses the existing snapshot/fetch path. + +Same-page visits retain the cancellable `livewire:navigate` and completion `livewire:navigated` events. They do not emit the page-swap event `livewire:navigating`. + +Validation: +- Reproduced unwanted hover prefetching before the fix with a failing browser regression. +- 29 focused Dusk browser tests pass with 260 assertions, including 11 new tests for state/input preservation, hover, keyboard and programmatic navigation, repeated/empty fragments, cancellation, scroll preservation, nested scroll containers, query changes, page refresh, and history across other pages. +- Existing navigation lifecycle, snapshot-cache, refresh, error-page history, and fragment-scroll checks pass. PHPUnit reports two deprecations. +- Rebuilt JavaScript assets for browser verification. Generated bundles are excluded from the commit. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `31b12dd0f4b4`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10693/tests/oracle.patch b/tasks/livewire__livewire-10693/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..554be66006cb3afd205c8e737766d850dd091074 --- /dev/null +++ b/tasks/livewire__livewire-10693/tests/oracle.patch @@ -0,0 +1,502 @@ +diff --git a/js/plugins/navigate/history.js b/js/plugins/navigate/history.js +index 030bc3a1..12ca01ff 100644 +--- a/js/plugins/navigate/history.js ++++ b/js/plugins/navigate/history.js +@@ -9,6 +9,7 @@ class Snapshot { + + let snapshotCache = { + currentKey: null, ++ currentDocumentId: Math.random(), + currentUrl: null, + keys: [], + lookup: {}, +@@ -81,7 +82,8 @@ export function updateCurrentPageHtmlInSnapshotCacheForLaterBackButtonClicks(key + + export function whenTheBackOrForwardButtonIsClicked( + registerFallback, +- handleHtml ++ handleHtml, ++ handleFragment + ) { + let fallback + +@@ -103,6 +105,19 @@ export function whenTheBackOrForwardButtonIsClicked( + + if (! alpine.snapshotIdx) return + ++ // Fragment entries belong to the same live page. Let the browser restore ++ // their scroll position without reconstructing the page from a snapshot. ++ if (alpine.documentId && alpine.documentId === snapshotCache.currentDocumentId) { ++ let snapshot = snapshotCache.has(alpine.snapshotIdx) && snapshotCache.retrieve(alpine.snapshotIdx) ++ ++ handleFragment(new URL(window.location.href), snapshot?.html, snapshotCache.currentUrl, snapshotCache.currentKey) ++ ++ snapshotCache.currentKey = alpine.snapshotIdx ++ snapshotCache.currentUrl = new URL(window.location.href) ++ ++ return ++ } ++ + if (snapshotCache.has(alpine.snapshotIdx)) { + let snapshot = snapshotCache.retrieve(alpine.snapshotIdx) + +@@ -110,9 +125,11 @@ export function whenTheBackOrForwardButtonIsClicked( + + snapshotCache.currentKey = alpine.snapshotIdx + snapshotCache.currentUrl = snapshot.url ++ snapshotCache.currentDocumentId = alpine.documentId ?? Math.random() + } else { + snapshotCache.currentKey = null + snapshotCache.currentUrl = null ++ snapshotCache.currentDocumentId = alpine.documentId ?? Math.random() + + fallback(alpine.url) + } +@@ -126,15 +143,17 @@ export function updateUrlAndStoreLatestHtmlForFutureBackButtons( + pushUrl(destination, html) + } + +-export function pushUrl(url, html) { +- updateUrl('pushState', url, html) ++export function pushUrl(url, html, { sameDocument = false } = {}) { ++ updateUrl('pushState', url, html, { sameDocument }) + } + + export function replaceUrl(url, html) { + updateUrl('replaceState', url, html) + } + +-function updateUrl(method, url, html) { ++function updateUrl(method, url, html, { sameDocument = false } = {}) { ++ if (method === 'pushState' && ! sameDocument) snapshotCache.currentDocumentId = Math.random() ++ + let key = url.toString() + '-' + Math.random() + + method === 'pushState' +@@ -150,7 +169,7 @@ function updateUrl(method, url, html) { + } + }) + +- historyCoordinator[method](url, { snapshotIdx: key, url: url.toString() }) ++ historyCoordinator[method](url, { snapshotIdx: key, url: url.toString(), documentId: snapshotCache.currentDocumentId }) + + snapshotCache.currentKey = key + snapshotCache.currentUrl = url +diff --git a/js/plugins/navigate/index.js b/js/plugins/navigate/index.js +index d89dd486..7ed9cfd5 100644 +--- a/js/plugins/navigate/index.js ++++ b/js/plugins/navigate/index.js +@@ -1,6 +1,6 @@ +-import { replaceUrl, updateCurrentPageHtmlInHistoryStateForLaterBackButtonClicks, updateCurrentPageHtmlInSnapshotCacheForLaterBackButtonClicks, updateUrlAndStoreLatestHtmlForFutureBackButtons, whenTheBackOrForwardButtonIsClicked } from "./history" ++import { pushUrl, replaceUrl, updateCurrentPageHtmlInHistoryStateForLaterBackButtonClicks, updateCurrentPageHtmlInSnapshotCacheForLaterBackButtonClicks, updateUrlAndStoreLatestHtmlForFutureBackButtons, whenTheBackOrForwardButtonIsClicked } from "./history" + import { getPretchedHtmlOr, prefetchHtml, storeThePrefetchedHtmlForWhenALinkIsClicked } from "./prefetch" +-import { createUrlObjectFromString, extractDestinationFromLink, isSameOrigin, linkShouldBeHandledNatively, visitNatively, whenThisLinkIsHoveredFor, whenThisLinkIsPressed } from "./links" ++import { createUrlObjectFromString, extractDestinationFromLink, isSameOrigin, isSamePageFragment, linkShouldBeHandledNatively, visitNatively, whenThisLinkIsHoveredFor, whenThisLinkIsPressed } from "./links" + import { isTeleportTarget, packUpPersistedTeleports, removeAnyLeftOverStaleTeleportTargets, unPackPersistedTeleports } from "./teleport" + import { restoreScrollPositionOrScrollToTop, storeScrollInformationInHtmlBeforeNavigatingAway } from "./scroll" + import { isPersistedElement, putPersistantElementsBack, storePersistantElementsForLater } from "./persist" +@@ -50,7 +50,7 @@ export default function (Alpine) { + shouldPrefetchOnHover && whenThisLinkIsHoveredFor(el, 60, () => { + let destination = extractDestinationFromLink(el) + +- if (linkShouldBeHandledNatively(el, destination)) return ++ if (linkShouldBeHandledNatively(el, destination) || isSamePageFragment(destination)) return + + prefetchHtml(destination, (html, finalDestination) => { + storeThePrefetchedHtmlForWhenALinkIsClicked(html, destination, finalDestination) +@@ -62,7 +62,7 @@ export default function (Alpine) { + whenThisLinkIsPressed(el, (whenItIsReleased) => { + let destination = extractDestinationFromLink(el) + +- prefetchHtml(destination, (html, finalDestination) => { ++ if (! isSamePageFragment(destination)) prefetchHtml(destination, (html, finalDestination) => { + storeThePrefetchedHtmlForWhenALinkIsClicked(html, destination, finalDestination) + }, () => { + showProgressBar && finishAndHideProgressBar() +@@ -83,6 +83,24 @@ export default function (Alpine) { + function navigateTo(destination, { preserveScroll = false, shouldPushToHistoryState = true }) { + let navigation = startNavigation() + ++ if (shouldPushToHistoryState && isSamePageFragment(destination)) { ++ navigation.ready() ++ ++ storeScrollInformationInHtmlBeforeNavigatingAway() ++ updateCurrentPageHtmlInHistoryStateForLaterBackButtonClicks() ++ ++ if (destination.href !== window.location.href) { ++ pushUrl(destination, document.documentElement.outerHTML, { sameDocument: true }) ++ } ++ ++ restoreScrollPositionOrScrollToTop({ scrollToFragment: ! preserveScroll }) ++ ++ fireEventForOtherLibrariesToHookInto('alpine:navigated') ++ navigation.finish() ++ ++ return ++ } ++ + showProgressBar && showAndStartProgressBar() + + fetchHtmlOrUsePrefetchedHtml(destination, (html, finalDestination) => { +@@ -251,6 +269,19 @@ export default function (Alpine) { + }) + }) + }, ++ (destination, snapshotHtml, currentPageUrl, currentPageKey) => { ++ let prevented = fireEventForOtherLibrariesToHookInto('alpine:navigate', { ++ url: destination, history: true, cached: true, ++ }) ++ ++ if (prevented) return ++ ++ storeScrollInformationInHtmlBeforeNavigatingAway() ++ updateCurrentPageHtmlInSnapshotCacheForLaterBackButtonClicks(currentPageKey, currentPageUrl) ++ restoreScrollPositionOrScrollToTop({ snapshotHtml }) ++ ++ fireEventForOtherLibrariesToHookInto('alpine:navigated') ++ }, + ) + + // Because DOMContentLoaded is fired on first load, +diff --git a/js/plugins/navigate/links.js b/js/plugins/navigate/links.js +index 1722c566..7048ade6 100644 +--- a/js/plugins/navigate/links.js ++++ b/js/plugins/navigate/links.js +@@ -87,6 +87,13 @@ export function isSameOrigin(destination) { + return !! destination && destination.origin === window.location.origin + } + ++export function isSamePageFragment(destination) { ++ return isSameOrigin(destination) ++ && destination.pathname === window.location.pathname ++ && destination.search === window.location.search ++ && destination.href.includes('#') ++} ++ + export function visitNatively(destination) { + window.location.href = destination.href + } +diff --git a/js/plugins/navigate/scroll.js b/js/plugins/navigate/scroll.js +index c5b6107f..bd529dab 100644 +--- a/js/plugins/navigate/scroll.js ++++ b/js/plugins/navigate/scroll.js +@@ -4,19 +4,30 @@ export function storeScrollInformationInHtmlBeforeNavigatingAway() { + document.body.setAttribute('data-scroll-y', document.body.scrollTop) + + document.querySelectorAll(['[x-navigate\\:scroll]', '[wire\\:navigate\\:scroll]']).forEach(el => { ++ // Match saved scroll positions to live containers during fragment history visits. ++ if (! el.hasAttribute('data-scroll-id')) el.setAttribute('data-scroll-id', Math.random()) ++ + el.setAttribute('data-scroll-x', el.scrollLeft) + el.setAttribute('data-scroll-y', el.scrollTop) + }) + } + +-export function restoreScrollPositionOrScrollToTop() { ++export function restoreScrollPositionOrScrollToTop({ scrollToFragment = false, snapshotHtml = null } = {}) { ++ let savedElements = snapshotHtml ++ ? new DOMParser().parseFromString(snapshotHtml, 'text/html').querySelectorAll('[data-scroll-id]') ++ : [] ++ ++ let savedScroll = new Map(Array.from(savedElements, el => [el.getAttribute('data-scroll-id'), el])) ++ + let scroll = el => { +- if (! el.hasAttribute('data-scroll-x')) { ++ let source = savedScroll.get(el.getAttribute('data-scroll-id')) || el ++ ++ if (! source.hasAttribute('data-scroll-x')) { + window.scrollTo({ top: 0, left: 0, behavior: 'instant' }) + } else { + el.scrollTo({ +- top: Number(el.getAttribute('data-scroll-y')), +- left: Number(el.getAttribute('data-scroll-x')), ++ top: Number(source.getAttribute('data-scroll-y')), ++ left: Number(source.getAttribute('data-scroll-x')), + behavior: 'instant', + }) + el.removeAttribute('data-scroll-x') +@@ -32,7 +43,9 @@ export function restoreScrollPositionOrScrollToTop() { + + document.querySelectorAll(['[x-navigate\\:scroll]', '[wire\\:navigate\\:scroll]']).forEach(scroll) + +- if (shouldScrollToFragment) { ++ if (scrollToFragment && ! window.location.hash) { ++ window.scrollTo({ top: 0, left: 0, behavior: 'instant' }) ++ } else if (shouldScrollToFragment || scrollToFragment) { + getFragmentTarget()?.scrollIntoView({ behavior: 'instant' }) + } + }) +diff --git a/src/Features/SupportNavigate/FragmentBrowserTest.php b/src/Features/SupportNavigate/FragmentBrowserTest.php +new file mode 100644 +index 00000000..06962c97 +--- /dev/null ++++ b/src/Features/SupportNavigate/FragmentBrowserTest.php +@@ -0,0 +1,268 @@ ++middleware('web'); ++ Route::get('/fragment-other', FragmentPage::class)->middleware('web'); ++ }; ++ } ++ ++ public function test_same_page_fragment_links_do_not_fetch_or_swap_the_page() ++ { ++ $this->browse(function ($browser) { ++ $browser->visit('/fragment')->click('@increment')->type('@draft', 'Unsaved draft'); ++ $browser->script('window.fragmentRequests = 0; Livewire.hook("navigate.request", () => window.fragmentRequests++)'); ++ ++ $browser ++ ->waitForNoNavigatePrefetchRequest()->mouseover('@comments') ++ ->waitForNavigate()->click('@comments') ++ ->assertFragmentIs('comments') ++ ->assertInViewPort('@comments-target') ++ ->assertSeeIn('@count', '1') ++ ->assertInputValue('@draft', 'Unsaved draft') ++ ->assertScript('window.fragmentRequests', 0) ++ ->assertConsoleLogHasNoErrors(); ++ }); ++ } ++ ++ public function test_fragment_history_keeps_the_live_page_and_restores_scroll() ++ { ++ $this->browse(function ($browser) { ++ $browser->visit('/fragment')->click('@increment'); ++ $browser->script('window.fragmentRequests = 0; Livewire.hook("navigate.request", () => window.fragmentRequests++)'); ++ ++ $browser ++ ->waitForNavigate()->click('@comments') ++ ->assertInViewPort('@comments-target') ++ ->waitForNavigate()->click('@replies') ++ ->assertInViewPort('@replies-target') ++ ->waitForNavigate()->back() ++ ->assertFragmentIs('comments') ++ ->assertInViewPort('@comments-target') ++ ->assertSeeIn('@count', '1') ++ ->waitForNavigate()->back() ++ ->assertFragmentIs('') ++ ->assertScript('window.scrollY', 0) ++ ->assertSeeIn('@count', '1') ++ ->waitForNavigate()->forward() ++ ->assertFragmentIs('comments') ++ ->assertInViewPort('@comments-target') ++ ->assertSeeIn('@count', '1') ++ ->assertScript('window.fragmentRequests', 0); ++ }); ++ } ++ ++ public function test_fragment_history_works_after_visiting_another_page() ++ { ++ $this->browse(function ($browser) { ++ $browser ++ ->visit('/fragment') ++ ->waitForNavigate()->click('@comments') ++ ->waitForNavigate()->click('@other') ++ ->assertPathIs('/fragment-other') ++ ->waitForNavigate()->back() ++ ->assertPathIs('/fragment') ++ ->assertFragmentIs('comments') ++ ->assertInViewPort('@comments-target') ++ ->click('@increment') ++ ->waitForNavigate()->back() ++ ->assertFragmentIs('') ++ ->assertSeeIn('@count', '1') ++ ->waitForNavigate()->forward() ++ ->assertFragmentIs('comments') ++ ->assertSeeIn('@count', '1') ++ ->waitForNavigate()->forward() ++ ->assertPathIs('/fragment-other'); ++ }); ++ } ++ ++ public function test_programmatic_fragment_navigation_and_preserve_scroll() ++ { ++ $this->browse(function ($browser) { ++ $browser->visit('/fragment')->click('@increment'); ++ $browser->script('window.fragmentRequests = 0; Livewire.hook("navigate.request", () => window.fragmentRequests++)'); ++ ++ $browser ++ ->waitForNavigate()->click('@preserve') ++ ->assertFragmentIs('comments') ++ ->assertScript('window.scrollY', 0) ++ ->waitForNavigate()->click('@programmatic-preserve') ++ ->assertFragmentIs('replies') ++ ->assertScript('window.scrollY', 0) ++ ->waitForNavigate()->click('@programmatic') ++ ->assertFragmentIs('replies') ++ ->assertInViewPort('@replies-target') ++ ->assertSeeIn('@count', '1') ++ ->assertScript('window.fragmentRequests', 0); ++ }); ++ } ++ ++ public function test_fragment_links_support_keyboard_activation_and_repeated_clicks() ++ { ++ $this->browse(function ($browser) { ++ $browser->visit('/fragment')->click('@increment'); ++ $browser->script('window.fragmentRequests = 0; window.fragmentHistoryLength = history.length; Livewire.hook("navigate.request", () => window.fragmentRequests++)'); ++ ++ $browser ++ ->waitForNavigate()->keys('@comments', '{enter}') ++ ->assertFragmentIs('comments') ++ ->assertInViewPort('@comments-target'); ++ ++ $browser->script('window.scrollTo(0, 0)'); ++ ++ $browser ++ ->waitForNavigate()->click('@comments') ++ ->assertInViewPort('@comments-target') ++ ->assertScript('history.length === window.fragmentHistoryLength + 1', true) ++ ->assertSeeIn('@count', '1') ++ ->assertScript('window.fragmentRequests', 0); ++ }); ++ } ++ ++ public function test_empty_fragments_scroll_to_top_without_swapping() ++ { ++ $this->browse(function ($browser) { ++ $browser ++ ->visit('/fragment') ++ ->click('@increment') ++ ->waitForNavigate()->click('@comments') ++ ->assertInViewPort('@comments-target') ++ ->waitForNavigate()->click('@top') ++ ->assertScript('window.scrollY', 0) ++ ->assertSeeIn('@count', '1'); ++ }); ++ } ++ ++ public function test_fragment_navigation_is_cancellable_and_does_not_fire_swap_events() ++ { ++ $this->browse(function ($browser) { ++ $browser->visit('/fragment'); ++ $browser->script(<<<'JS' ++ window.fragmentRequests = 0; ++ window.fragmentSwaps = 0; ++ Livewire.hook('navigate.request', () => window.fragmentRequests++); ++ document.addEventListener('livewire:navigating', () => window.fragmentSwaps++); ++ document.addEventListener('livewire:navigate', event => event.preventDefault(), { once: true }); ++ JS); ++ ++ $browser ++ ->click('@comments') ++ ->assertFragmentIs('') ++ ->assertScript('window.scrollY', 0) ++ ->waitForNavigate()->click('@comments') ++ ->assertFragmentIs('comments') ++ ->assertInViewPort('@comments-target') ++ ->assertScript('window.fragmentRequests', 0) ++ ->assertScript('window.fragmentSwaps', 0); ++ }); ++ } ++ ++ public function test_fragment_history_restores_marked_scroll_containers() ++ { ++ $this->browse(function ($browser) { ++ $browser->visit('/fragment'); ++ $browser->script('document.getElementById("pane").scrollTop = 100'); ++ ++ $browser->waitForNavigate()->click('@comments'); ++ $browser->script('document.getElementById("pane").scrollTop = 200'); ++ ++ $browser ++ ->waitForNavigate()->back() ++ ->assertScript('document.getElementById("pane").scrollTop', 100) ++ ->waitForNavigate()->forward() ++ ->assertScript('document.getElementById("pane").scrollTop', 200); ++ }); ++ } ++ ++ public function test_fragment_history_works_after_a_browser_refresh() ++ { ++ $this->browse(function ($browser) { ++ $browser ++ ->visit('/fragment') ++ ->waitForNavigate()->click('@comments') ++ ->waitForNavigate()->click('@replies') ++ ->refresh() ++ ->waitForNavigate()->back() ++ ->assertFragmentIs('comments') ++ ->assertInViewPort('@comments-target') ++ ->click('@increment') ++ ->waitForNavigate()->back() ++ ->assertFragmentIs('') ++ ->assertSeeIn('@count', '1'); ++ }); ++ } ++ ++ public function test_visiting_the_same_url_without_a_fragment_still_swaps_the_page() ++ { ++ $this->browse(function ($browser) { ++ $browser ++ ->visit('/fragment') ++ ->click('@increment') ++ ->waitForNavigate()->click('@reload') ++ ->assertSeeIn('@count', '0') ++ ->click('@increment') ++ ->click('@increment') ++ ->waitForNavigate()->back() ++ ->assertSeeIn('@count', '0'); ++ }); ++ } ++ ++ public function test_a_query_string_change_still_fetches_and_swaps_the_page() ++ { ++ $this->browse(function ($browser) { ++ $browser->visit('/fragment')->click('@increment'); ++ $browser->script('window.fragmentRequests = 0; Livewire.hook("navigate.request", () => window.fragmentRequests++)'); ++ ++ $browser ++ ->waitForNavigate()->click('@query') ++ ->assertQueryStringHas('page', '2') ++ ->assertFragmentIs('comments') ++ ->assertInViewPort('@comments-target') ++ ->assertSeeIn('@count', '0') ++ ->assertScript('window.fragmentRequests', 1); ++ }); ++ } ++} ++ ++class FragmentPage extends Component ++{ ++ public function render() ++ { ++ return <<<'HTML' ++
++ ++
++
Scrollable pane
++
++
++
Comments
++
++
Replies
++
++
++ HTML; ++ } ++} diff --git a/tasks/livewire__livewire-10693/tests/test.sh b/tasks/livewire__livewire-10693/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..d9e104ac10ce04afb00a3ea9d4a390a83a77d23b --- /dev/null +++ b/tasks/livewire__livewire-10693/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 31b12dd0f4b44bfa9a5c2fb3d13dd93ad35dad3f > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/livewire__livewire-10693/tests/verifier.py b/tasks/livewire__livewire-10693/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/livewire__livewire-10693/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/livewire__livewire-10696/environment/Dockerfile b/tasks/livewire__livewire-10696/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..4cb4d67f06b40da9494e6206d3e6c4356e362c80 --- /dev/null +++ b/tasks/livewire__livewire-10696/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/livewire/livewire.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/livewire/livewire.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/livewire/livewire.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 80dccd98f3109c4f99162877d8495c7482cdcb61 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 80dccd98f3109c4f99162877d8495c7482cdcb61 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 80dccd98f3109c4f99162877d8495c7482cdcb61 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/livewire__livewire-10696/instruction.md b/tasks/livewire__livewire-10696/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..94bad8edccc2cd930cb99941e7134f6ff1908d00 --- /dev/null +++ b/tasks/livewire__livewire-10696/instruction.md @@ -0,0 +1,65 @@ +# Issue + +**Title:** [4.x] Keep failed requests fired without a caller from surfacing as unhandled promise rejections + +## Description + +Livewire fires plenty of requests on its own behalf: `#[On]` listeners, `wire:model.live`, `wire:click="$set(...)"`, file uploads. None of them has a caller waiting on the action promise. When one of those requests fails (a 500 from a throwing handler, a 419 after a `release_token` change or session expiry, a 4xx from middleware), the action promise is rejected with `{ status, body, json, errors }` *after* Livewire has already surfaced the failure. Nobody owns that promise, so the browser reports: + +``` +Uncaught (in promise) {status: 419, body: '…', json: {…}, errors: null} +``` + +on top of the error modal or the "page has expired" dialog. Each one also fires `unhandledrejection`, which error trackers (Sentry, Bugsnag, in-house reporters) file as a page error. After a deployment that rotates the release token, a stale page produces one per listener or live input. + +- Render a component with an `#[On('foo')]` listener, an ``, or a `wire:click="$set(...)"` +- Make the request fail (throw in the handler, expire the session, rotate the release token) +- The Livewire error modal appears **and** the console shows `Uncaught (in promise) {status: …}` + +```php +#[On('foo')] +public function onFoo() +{ + throw new \Exception('The listener failed.'); +} +``` + +```html + +``` + +## Findings + +- Livewire already has a policy for this. `evaluateActionExpression()` in `js/evaluator.js` silently `.catch()`es any promise carrying the `_livewireAction` marker ("Silently catch Livewire request failures. These are handled by Livewire at the request level"). That covers `wire:click`, `wire:poll`, `wire:init` and `wire:intersect`. +- Every path that doesn't go through the evaluator leaks: `supportListeners.js` (`$wire.call('__dispatch', …)`), `wire-model.js` (`$wire.$commit()`), and `supportFileUploads.js` (`$wire.call('_startUpload', …)` and friends). +- Paths that *do* go through the evaluator still leak when the `$wire` method is an `async` wrapper, because the wrapper hands back a copy of the action promise without the marker. `$set` and `$call` are still `async`, so `wire:click="$set('open', true)"` and `wire:click="$toggle('open')"` leak today. #10428 fixed exactly this for `$refresh` and `$commit`. +- The action promise is only ever settled through `Action.resolvePromise()` / `Action.rejectPromise()`, and every rejection carries the same `{ status, body, json, errors }` shape, so there is nothing else for a shape check to distinguish. + +## Potential solutions + +- **Catch-and-rethrow shim in `supportListeners.js`** (this PR's first cut). Fixes listeners only, re-implements the `_livewireAction` policy as a structural `isRequestFailure()` check that has to track the rejection shape, and leaves `wire:model.live`, `$set`, `$toggle` and uploads producing the same noise. +- **`.catch(() => {})` at every internal call site.** Eight call sites today, and the next internal caller forgets it. +- **Mark the promise as handled where it is created.** One line in `Action`; the `_livewireAction` marker and the evaluator special case become redundant. + +## Proposed solution + +`Action` attaches a no-op rejection handler to its own promise when it is constructed. That marks the promise as handled, so a discarded one never becomes an `unhandledrejection`, while callers that `await` or `.catch()` it still receive the exact same rejection (attaching a handler doesn't change the promise's state or what other consumers see). + +For that to cover everything, each `$wire` entry point has to hand back the action's own promise rather than an `async` wrapper's copy, so `$set` and `$call` drop their `async` the same way #10428 did for `$refresh` and `$commit`. With that in place the `_livewireAction` marker and the `if (result._livewireAction) result.catch(...)` branch in the evaluator are dead and removed, and `supportListeners.js` goes back to its original two lines. + +Tests: + +- `SupportEvents/BrowserTest`: a listener whose handler throws still shows the error modal and fires `unhandledrejection` zero times. +- `HandleRequests/BrowserTest`: the same for `wire:model.live` and `wire:click="$set(...)"` (fails on 4.x with 2 rejections), plus a test that `$wire.explode().catch(...)` still receives the rejection with `status: 500`, so callers that handle failures keep getting them. + +--- + +One behaviour worth knowing about: a `#[Json]` method that is fired and forgotten (no `await`, no `.catch()`) and then fails is now silent, where before it logged `Uncaught (in promise) {status: 403, …}`. `#[Json]` methods are meant to be awaited, and this matches what `wire:click="jsonMethod"` already did, but it is the one place the console gets quieter without a modal taking its place. + +🤖 Generated with [Claude Code](https://claude.com/claude-code) + +https://claude.ai/code/session_011y8NkAhu4j2vcTVy4fbrDw + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `80dccd98f310`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10696/solution/patch.diff b/tasks/livewire__livewire-10696/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..a32f0ecc33ba9cc09d99d11b8da7a696e010b8dd --- /dev/null +++ b/tasks/livewire__livewire-10696/solution/patch.diff @@ -0,0 +1,169 @@ +diff --git a/js/$wire.js b/js/$wire.js +index b5e86f58..0f7a0f12 100644 +--- a/js/$wire.js ++++ b/js/$wire.js +@@ -197,7 +197,7 @@ wireProperty('$js', (component) => { + }) + }) + +-wireProperty('$set', (component) => async (property, value, live = true) => { ++wireProperty('$set', (component) => (property, value, live = true) => { + dataSet(component.reactive, property, value) + + // If "live", send a request, queueing the property update to happen first +@@ -261,8 +261,8 @@ wireProperty('$interceptRequest', (component) => (actionNameOrCallback, maybeCal + + wireProperty('$errors', (component) => getErrorsObject(component)) + +-wireProperty('$call', (component) => async (method, ...params) => { +- return await component.$wire[method](...params) ++wireProperty('$call', (component) => (method, ...params) => { ++ return component.$wire[method](...params) + }) + + wireProperty('$island', (component) => (name, options = {}) => { +diff --git a/js/evaluator.js b/js/evaluator.js +index 97857b9d..cb233e30 100644 +--- a/js/evaluator.js ++++ b/js/evaluator.js +@@ -68,15 +68,7 @@ export function evaluateActionExpression(el, expression, options = {}) { + let contextualExpression = contextualizeExpression(expression, el, ! isEvaluatingReactiveExpression()) + + try { +- let result = Alpine.evaluateRaw(el, contextualExpression, options) +- +- // Silently catch Livewire request failures. These are handled by +- // Livewire at the request level... +- if (result instanceof Promise && result._livewireAction) { +- result.catch(() => {}) +- } +- +- return result ++ return Alpine.evaluateRaw(el, contextualExpression, options) + } catch (error) { + reportExpressionError(error, expression, el) + } +diff --git a/js/request/action.js b/js/request/action.js +index a37a961b..929ac62e 100644 +--- a/js/request/action.js ++++ b/js/request/action.js +@@ -30,7 +30,11 @@ export default class Action { + this.promiseResolution = { resolve, reject } + }) + +- this.promise._livewireAction = this ++ // Livewire surfaces failed requests itself (error modal, expired-page dialog, ++ // interceptors), so a caller that discards this promise shouldn't also get an ++ // "Uncaught (in promise)". This marks it handled without hiding the rejection ++ // from callers that await it... ++ this.promise.catch(() => {}) + } + + cancel() { +diff --git a/src/Features/SupportEvents/BrowserTest.php b/src/Features/SupportEvents/BrowserTest.php +index 1cef22d1..724a98ec 100644 +--- a/src/Features/SupportEvents/BrowserTest.php ++++ b/src/Features/SupportEvents/BrowserTest.php +@@ -611,4 +611,29 @@ class BrowserTest extends BrowserTestCase + ->click('@button') + ->waitForTextIn('@output', 'baz'); + } ++ ++ public function test_a_failed_listener_request_does_not_leave_an_unhandled_promise_rejection() ++ { ++ Livewire::visit(new class extends Component { ++ #[On('foo')] ++ public function onFoo() ++ { ++ throw new \Exception('The listener failed.'); ++ } ++ ++ public function render() ++ { ++ return <<<'HTML' ++
++ ++
++ HTML; ++ } ++ }) ++ ->tap(fn ($browser) => $browser->script('window.unhandledRejections = 0; window.addEventListener("unhandledrejection", () => window.unhandledRejections++)')) ++ ->click('@button') ++ ->waitFor('#livewire-error') ++ ->pause(250) ++ ->assertScript('window.unhandledRejections', 0); ++ } + } +diff --git a/src/Mechanisms/HandleRequests/BrowserTest.php b/src/Mechanisms/HandleRequests/BrowserTest.php +index f660b25f..062457bf 100644 +--- a/src/Mechanisms/HandleRequests/BrowserTest.php ++++ b/src/Mechanisms/HandleRequests/BrowserTest.php +@@ -3,6 +3,7 @@ + namespace Livewire\Mechanisms\HandleRequests; + + use Illuminate\Support\Facades\Route; ++use Livewire\Component; + use Livewire\Livewire; + + class BrowserTest extends \Tests\BrowserTestCase +@@ -38,4 +39,60 @@ class BrowserTest extends \Tests\BrowserTestCase + ->assertSeeIn('@output', 5) + ; + } ++ ++ public function test_failed_requests_fired_without_a_caller_do_not_leave_unhandled_promise_rejections() ++ { ++ Livewire::visit(new class extends Component { ++ public $value = ''; ++ ++ public function updatedValue() ++ { ++ throw new \Exception('The update failed.'); ++ } ++ ++ public function render() ++ { ++ return <<<'HTML' ++
++ ++ ++
++ HTML; ++ } ++ }) ++ ->tap(fn ($browser) => $browser->script('window.unhandledRejections = 0; window.addEventListener("unhandledrejection", () => window.unhandledRejections++)')) ++ ->type('@input', 'foo') ++ ->waitFor('#livewire-error') ++ ->tap(fn ($browser) => $browser->script("document.getElementById('livewire-error').close()")) ++ ->waitUntilMissing('#livewire-error') ++ ->click('@set') ++ ->waitFor('#livewire-error') ++ ->pause(250) ++ ->assertScript('window.unhandledRejections', 0); ++ } ++ ++ public function test_a_failed_request_still_rejects_the_action_promise_for_callers_that_handle_it() ++ { ++ Livewire::visit(new class extends Component { ++ public function explode() ++ { ++ throw new \Exception('The action failed.'); ++ } ++ ++ public function render() ++ { ++ return <<<'HTML' ++
++ ++
++ HTML; ++ } ++ }) ++ ->tap(fn ($browser) => $browser->script('window.unhandledRejections = 0; window.addEventListener("unhandledrejection", () => window.unhandledRejections++)')) ++ ->click('@button') ++ ->waitFor('#livewire-error') ++ ->pause(250) ++ ->assertScript('window.caught', 500) ++ ->assertScript('window.unhandledRejections', 0); ++ } + } diff --git a/tasks/livewire__livewire-10696/solution/solve.sh b/tasks/livewire__livewire-10696/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/livewire__livewire-10696/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/livewire__livewire-10696/task.toml b/tasks/livewire__livewire-10696/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..045f03b6531c36c7e2dd192e00868b7a910c1fe4 --- /dev/null +++ b/tasks/livewire__livewire-10696/task.toml @@ -0,0 +1,72 @@ +version = "1.0" + +[task] +name = "trending/livewire__livewire-10696" +description = "[4.x] Keep failed requests fired without a caller from surfacing as unhandled promise rejections" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "livewire", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "livewire/livewire" +ref = "80dccd98f3109c4f99162877d8495c7482cdcb61" +reference = "https://github.com/livewire/livewire/pull/10696" +source_access = "auto" +built_at = "2026-11-16T16:09:51.491566+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:5039e3e469029917eb85133d73c8e90809cc7c10ce3fe91e66a25a574a0c76ce" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-10T13:00:04Z" +diff_format = "unified" +context_files = [ + "js/$wire.js", + "js/evaluator.js", + "js/request/action.js", + "src/Features/SupportEvents/BrowserTest.php", + "src/Mechanisms/HandleRequests/BrowserTest.php", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 104 +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.412413+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:b25e03bbc2b33c4d3f486679a3196e2364e42a28fd2f205ad6e781d2be96263f" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/livewire__livewire-10696/tests/capture.py b/tasks/livewire__livewire-10696/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/livewire__livewire-10696/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/livewire__livewire-10696/tests/instruction.md b/tasks/livewire__livewire-10696/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..94bad8edccc2cd930cb99941e7134f6ff1908d00 --- /dev/null +++ b/tasks/livewire__livewire-10696/tests/instruction.md @@ -0,0 +1,65 @@ +# Issue + +**Title:** [4.x] Keep failed requests fired without a caller from surfacing as unhandled promise rejections + +## Description + +Livewire fires plenty of requests on its own behalf: `#[On]` listeners, `wire:model.live`, `wire:click="$set(...)"`, file uploads. None of them has a caller waiting on the action promise. When one of those requests fails (a 500 from a throwing handler, a 419 after a `release_token` change or session expiry, a 4xx from middleware), the action promise is rejected with `{ status, body, json, errors }` *after* Livewire has already surfaced the failure. Nobody owns that promise, so the browser reports: + +``` +Uncaught (in promise) {status: 419, body: '…', json: {…}, errors: null} +``` + +on top of the error modal or the "page has expired" dialog. Each one also fires `unhandledrejection`, which error trackers (Sentry, Bugsnag, in-house reporters) file as a page error. After a deployment that rotates the release token, a stale page produces one per listener or live input. + +- Render a component with an `#[On('foo')]` listener, an ``, or a `wire:click="$set(...)"` +- Make the request fail (throw in the handler, expire the session, rotate the release token) +- The Livewire error modal appears **and** the console shows `Uncaught (in promise) {status: …}` + +```php +#[On('foo')] +public function onFoo() +{ + throw new \Exception('The listener failed.'); +} +``` + +```html + +``` + +## Findings + +- Livewire already has a policy for this. `evaluateActionExpression()` in `js/evaluator.js` silently `.catch()`es any promise carrying the `_livewireAction` marker ("Silently catch Livewire request failures. These are handled by Livewire at the request level"). That covers `wire:click`, `wire:poll`, `wire:init` and `wire:intersect`. +- Every path that doesn't go through the evaluator leaks: `supportListeners.js` (`$wire.call('__dispatch', …)`), `wire-model.js` (`$wire.$commit()`), and `supportFileUploads.js` (`$wire.call('_startUpload', …)` and friends). +- Paths that *do* go through the evaluator still leak when the `$wire` method is an `async` wrapper, because the wrapper hands back a copy of the action promise without the marker. `$set` and `$call` are still `async`, so `wire:click="$set('open', true)"` and `wire:click="$toggle('open')"` leak today. #10428 fixed exactly this for `$refresh` and `$commit`. +- The action promise is only ever settled through `Action.resolvePromise()` / `Action.rejectPromise()`, and every rejection carries the same `{ status, body, json, errors }` shape, so there is nothing else for a shape check to distinguish. + +## Potential solutions + +- **Catch-and-rethrow shim in `supportListeners.js`** (this PR's first cut). Fixes listeners only, re-implements the `_livewireAction` policy as a structural `isRequestFailure()` check that has to track the rejection shape, and leaves `wire:model.live`, `$set`, `$toggle` and uploads producing the same noise. +- **`.catch(() => {})` at every internal call site.** Eight call sites today, and the next internal caller forgets it. +- **Mark the promise as handled where it is created.** One line in `Action`; the `_livewireAction` marker and the evaluator special case become redundant. + +## Proposed solution + +`Action` attaches a no-op rejection handler to its own promise when it is constructed. That marks the promise as handled, so a discarded one never becomes an `unhandledrejection`, while callers that `await` or `.catch()` it still receive the exact same rejection (attaching a handler doesn't change the promise's state or what other consumers see). + +For that to cover everything, each `$wire` entry point has to hand back the action's own promise rather than an `async` wrapper's copy, so `$set` and `$call` drop their `async` the same way #10428 did for `$refresh` and `$commit`. With that in place the `_livewireAction` marker and the `if (result._livewireAction) result.catch(...)` branch in the evaluator are dead and removed, and `supportListeners.js` goes back to its original two lines. + +Tests: + +- `SupportEvents/BrowserTest`: a listener whose handler throws still shows the error modal and fires `unhandledrejection` zero times. +- `HandleRequests/BrowserTest`: the same for `wire:model.live` and `wire:click="$set(...)"` (fails on 4.x with 2 rejections), plus a test that `$wire.explode().catch(...)` still receives the rejection with `status: 500`, so callers that handle failures keep getting them. + +--- + +One behaviour worth knowing about: a `#[Json]` method that is fired and forgotten (no `await`, no `.catch()`) and then fails is now silent, where before it logged `Uncaught (in promise) {status: 403, …}`. `#[Json]` methods are meant to be awaited, and this matches what `wire:click="jsonMethod"` already did, but it is the one place the console gets quieter without a modal taking its place. + +🤖 Generated with [Claude Code](https://claude.com/claude-code) + +https://claude.ai/code/session_011y8NkAhu4j2vcTVy4fbrDw + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `80dccd98f310`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10696/tests/oracle.patch b/tasks/livewire__livewire-10696/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..a32f0ecc33ba9cc09d99d11b8da7a696e010b8dd --- /dev/null +++ b/tasks/livewire__livewire-10696/tests/oracle.patch @@ -0,0 +1,169 @@ +diff --git a/js/$wire.js b/js/$wire.js +index b5e86f58..0f7a0f12 100644 +--- a/js/$wire.js ++++ b/js/$wire.js +@@ -197,7 +197,7 @@ wireProperty('$js', (component) => { + }) + }) + +-wireProperty('$set', (component) => async (property, value, live = true) => { ++wireProperty('$set', (component) => (property, value, live = true) => { + dataSet(component.reactive, property, value) + + // If "live", send a request, queueing the property update to happen first +@@ -261,8 +261,8 @@ wireProperty('$interceptRequest', (component) => (actionNameOrCallback, maybeCal + + wireProperty('$errors', (component) => getErrorsObject(component)) + +-wireProperty('$call', (component) => async (method, ...params) => { +- return await component.$wire[method](...params) ++wireProperty('$call', (component) => (method, ...params) => { ++ return component.$wire[method](...params) + }) + + wireProperty('$island', (component) => (name, options = {}) => { +diff --git a/js/evaluator.js b/js/evaluator.js +index 97857b9d..cb233e30 100644 +--- a/js/evaluator.js ++++ b/js/evaluator.js +@@ -68,15 +68,7 @@ export function evaluateActionExpression(el, expression, options = {}) { + let contextualExpression = contextualizeExpression(expression, el, ! isEvaluatingReactiveExpression()) + + try { +- let result = Alpine.evaluateRaw(el, contextualExpression, options) +- +- // Silently catch Livewire request failures. These are handled by +- // Livewire at the request level... +- if (result instanceof Promise && result._livewireAction) { +- result.catch(() => {}) +- } +- +- return result ++ return Alpine.evaluateRaw(el, contextualExpression, options) + } catch (error) { + reportExpressionError(error, expression, el) + } +diff --git a/js/request/action.js b/js/request/action.js +index a37a961b..929ac62e 100644 +--- a/js/request/action.js ++++ b/js/request/action.js +@@ -30,7 +30,11 @@ export default class Action { + this.promiseResolution = { resolve, reject } + }) + +- this.promise._livewireAction = this ++ // Livewire surfaces failed requests itself (error modal, expired-page dialog, ++ // interceptors), so a caller that discards this promise shouldn't also get an ++ // "Uncaught (in promise)". This marks it handled without hiding the rejection ++ // from callers that await it... ++ this.promise.catch(() => {}) + } + + cancel() { +diff --git a/src/Features/SupportEvents/BrowserTest.php b/src/Features/SupportEvents/BrowserTest.php +index 1cef22d1..724a98ec 100644 +--- a/src/Features/SupportEvents/BrowserTest.php ++++ b/src/Features/SupportEvents/BrowserTest.php +@@ -611,4 +611,29 @@ class BrowserTest extends BrowserTestCase + ->click('@button') + ->waitForTextIn('@output', 'baz'); + } ++ ++ public function test_a_failed_listener_request_does_not_leave_an_unhandled_promise_rejection() ++ { ++ Livewire::visit(new class extends Component { ++ #[On('foo')] ++ public function onFoo() ++ { ++ throw new \Exception('The listener failed.'); ++ } ++ ++ public function render() ++ { ++ return <<<'HTML' ++
++ ++
++ HTML; ++ } ++ }) ++ ->tap(fn ($browser) => $browser->script('window.unhandledRejections = 0; window.addEventListener("unhandledrejection", () => window.unhandledRejections++)')) ++ ->click('@button') ++ ->waitFor('#livewire-error') ++ ->pause(250) ++ ->assertScript('window.unhandledRejections', 0); ++ } + } +diff --git a/src/Mechanisms/HandleRequests/BrowserTest.php b/src/Mechanisms/HandleRequests/BrowserTest.php +index f660b25f..062457bf 100644 +--- a/src/Mechanisms/HandleRequests/BrowserTest.php ++++ b/src/Mechanisms/HandleRequests/BrowserTest.php +@@ -3,6 +3,7 @@ + namespace Livewire\Mechanisms\HandleRequests; + + use Illuminate\Support\Facades\Route; ++use Livewire\Component; + use Livewire\Livewire; + + class BrowserTest extends \Tests\BrowserTestCase +@@ -38,4 +39,60 @@ class BrowserTest extends \Tests\BrowserTestCase + ->assertSeeIn('@output', 5) + ; + } ++ ++ public function test_failed_requests_fired_without_a_caller_do_not_leave_unhandled_promise_rejections() ++ { ++ Livewire::visit(new class extends Component { ++ public $value = ''; ++ ++ public function updatedValue() ++ { ++ throw new \Exception('The update failed.'); ++ } ++ ++ public function render() ++ { ++ return <<<'HTML' ++
++ ++ ++
++ HTML; ++ } ++ }) ++ ->tap(fn ($browser) => $browser->script('window.unhandledRejections = 0; window.addEventListener("unhandledrejection", () => window.unhandledRejections++)')) ++ ->type('@input', 'foo') ++ ->waitFor('#livewire-error') ++ ->tap(fn ($browser) => $browser->script("document.getElementById('livewire-error').close()")) ++ ->waitUntilMissing('#livewire-error') ++ ->click('@set') ++ ->waitFor('#livewire-error') ++ ->pause(250) ++ ->assertScript('window.unhandledRejections', 0); ++ } ++ ++ public function test_a_failed_request_still_rejects_the_action_promise_for_callers_that_handle_it() ++ { ++ Livewire::visit(new class extends Component { ++ public function explode() ++ { ++ throw new \Exception('The action failed.'); ++ } ++ ++ public function render() ++ { ++ return <<<'HTML' ++
++ ++
++ HTML; ++ } ++ }) ++ ->tap(fn ($browser) => $browser->script('window.unhandledRejections = 0; window.addEventListener("unhandledrejection", () => window.unhandledRejections++)')) ++ ->click('@button') ++ ->waitFor('#livewire-error') ++ ->pause(250) ++ ->assertScript('window.caught', 500) ++ ->assertScript('window.unhandledRejections', 0); ++ } + } diff --git a/tasks/livewire__livewire-10696/tests/test.sh b/tasks/livewire__livewire-10696/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3d87ef43179e63f81700a8dece1a65d30f2f4a15 --- /dev/null +++ b/tasks/livewire__livewire-10696/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 80dccd98f3109c4f99162877d8495c7482cdcb61 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/livewire__livewire-10696/tests/verifier.py b/tasks/livewire__livewire-10696/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/livewire__livewire-10696/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/livewire__livewire-10697/environment/Dockerfile b/tasks/livewire__livewire-10697/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..24eefddb12292b080cb889e01f09b60af40ad335 --- /dev/null +++ b/tasks/livewire__livewire-10697/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/livewire/livewire.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/livewire/livewire.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/livewire/livewire.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 31b12dd0f4b44bfa9a5c2fb3d13dd93ad35dad3f 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 31b12dd0f4b44bfa9a5c2fb3d13dd93ad35dad3f \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 31b12dd0f4b44bfa9a5c2fb3d13dd93ad35dad3f \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/livewire__livewire-10697/instruction.md b/tasks/livewire__livewire-10697/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c15a969a96ea6f7784983482a983d3219c677108 --- /dev/null +++ b/tasks/livewire__livewire-10697/instruction.md @@ -0,0 +1,17 @@ +# Issue + +**Title:** Upgrade Vitest to patched 4.1 line + +## Description + +Updates Vitest from 3.2.4 to the patched 4.1.11 line without taking the breaking 5.0 upgrade proposed by Dependabot in #10691. The 5.0 jump pulls Vite 8 and fails dependency installation against the repository esbuild pin. + +Verified locally: +- npm ci --ignore-scripts +- npm run build +- npm run test:run (110 passed, 1 skipped) +- git diff --check + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `31b12dd0f4b4`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10697/solution/patch.diff b/tasks/livewire__livewire-10697/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..dbeff520694d5249c4fb4266eb1749aa5d286135 --- /dev/null +++ b/tasks/livewire__livewire-10697/solution/patch.diff @@ -0,0 +1,1995 @@ +diff --git a/package-lock.json b/package-lock.json +index 2f324395..0788dec8 100644 +--- a/package-lock.json ++++ b/package-lock.json +@@ -25,7 +25,7 @@ + "brotli-size": "^4.0.0", + "esbuild": "^0.14.49", + "jsdom": "27.0.0", +- "vitest": "^3.2.4" ++ "vitest": "^4.1.11" + } + }, + "node_modules/@alpinejs/anchor": { +@@ -276,63 +276,71 @@ + "node": ">=20.19.0" + } + }, +- "node_modules/@esbuild/aix-ppc64": { +- "version": "0.27.4", +- "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.4.tgz", +- "integrity": "sha512-cQPwL2mp2nSmHHJlCyoXgHGhbEPMrEEU5xhkcy3Hs/O7nGZqEpZ2sUtLaL9MORLtDfRvVl2/3PAuEkYZH0Ty8Q==", ++ "node_modules/@esbuild/linux-loong64": { ++ "version": "0.14.54", ++ "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.14.54.tgz", ++ "integrity": "sha512-bZBrLAIX1kpWelV0XemxBZllyRmM6vgFQQG2GdNb+r3Fkp0FOh1NJSvekXDs7jq70k4euu1cryLMfU+mTXlEpw==", + "cpu": [ +- "ppc64" ++ "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ +- "aix" ++ "linux" + ], + "engines": { +- "node": ">=18" ++ "node": ">=12" + } + }, +- "node_modules/@esbuild/android-arm": { +- "version": "0.27.4", +- "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.27.4.tgz", +- "integrity": "sha512-X9bUgvxiC8CHAGKYufLIHGXPJWnr0OCdR0anD2e21vdvgCI8lIfqFbnoeOz7lBjdrAGUhqLZLcQo6MLhTO2DKQ==", +- "cpu": [ +- "arm" +- ], +- "dev": true, ++ "node_modules/@floating-ui/core": { ++ "version": "1.7.5", ++ "resolved": "https://registry.npmjs.org/@floating-ui/core/-/core-1.7.5.tgz", ++ "integrity": "sha512-1Ih4WTWyw0+lKyFMcBHGbb5U5FtuHJuujoyyr5zTaWS5EYMeT6Jb2AuDeftsCsEuchO+mM2ij5+q9crhydzLhQ==", + "license": "MIT", +- "optional": true, +- "os": [ +- "android" +- ], +- "engines": { +- "node": ">=18" ++ "dependencies": { ++ "@floating-ui/utils": "^0.2.11" + } + }, +- "node_modules/@esbuild/android-arm64": { +- "version": "0.27.4", +- "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.27.4.tgz", +- "integrity": "sha512-gdLscB7v75wRfu7QSm/zg6Rx29VLdy9eTr2t44sfTW7CxwAtQghZ4ZnqHk3/ogz7xao0QAgrkradbBzcqFPasw==", +- "cpu": [ +- "arm64" +- ], ++ "node_modules/@floating-ui/dom": { ++ "version": "1.7.6", ++ "resolved": "https://registry.npmjs.org/@floating-ui/dom/-/dom-1.7.6.tgz", ++ "integrity": "sha512-9gZSAI5XM36880PPMm//9dfiEngYoC6Am2izES1FF406YFsjvyBMmeJ2g4SAju3xWwtuynNRFL2s9hgxpLI5SQ==", ++ "license": "MIT", ++ "dependencies": { ++ "@floating-ui/core": "^1.7.5", ++ "@floating-ui/utils": "^0.2.11" ++ } ++ }, ++ "node_modules/@floating-ui/utils": { ++ "version": "0.2.11", ++ "resolved": "https://registry.npmjs.org/@floating-ui/utils/-/utils-0.2.11.tgz", ++ "integrity": "sha512-RiB/yIh78pcIxl6lLMG0CgBXAZ2Y0eVHqMPYugu+9U0AeT6YBeiJpf7lbdJNIugFP5SIjwNRgo4DhR1Qxi26Gg==", ++ "license": "MIT" ++ }, ++ "node_modules/@jridgewell/sourcemap-codec": { ++ "version": "1.6.0", ++ "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", ++ "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", ++ "dev": true, ++ "license": "MIT" ++ }, ++ "node_modules/@oxc-project/types": { ++ "version": "0.149.0", ++ "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.149.0.tgz", ++ "integrity": "sha512-Efcc+iF0j3Bf67YjEqIqWXbX5XddXoK/Mw4K1/JuXwRCZ8N16VR7iT23nlCc9XrveFVh/E5Rqs2StT0V8v9LdA==", + "dev": true, + "license": "MIT", +- "optional": true, +- "os": [ +- "android" +- ], +- "engines": { +- "node": ">=18" ++ "funding": { ++ "url": "https://github.com/sponsors/oxc-project" + } + }, +- "node_modules/@esbuild/android-x64": { +- "version": "0.27.4", +- "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.27.4.tgz", +- "integrity": "sha512-PzPFnBNVF292sfpfhiyiXCGSn9HZg5BcAz+ivBuSsl6Rk4ga1oEXAamhOXRFyMcjwr2DVtm40G65N3GLeH1Lvw==", ++ "node_modules/@rolldown/binding-android-arm-eabi": { ++ "version": "1.2.8", ++ "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.8.tgz", ++ "integrity": "sha512-tN5aztYkKCte4i5SIrrz5yK/HMjEuCqCSCJa418jOV8tZ1cBY3YF2otxB1ktPxzsLA1BeTqwapK0bfjxNvHJVw==", + "cpu": [ +- "x64" ++ "arm" + ], + "dev": true, + "license": "MIT", +@@ -341,13 +349,13 @@ + "android" + ], + "engines": { +- "node": ">=18" ++ "node": "^20.19.0 || >=22.12.0" + } + }, +- "node_modules/@esbuild/darwin-arm64": { +- "version": "0.27.4", +- "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.27.4.tgz", +- "integrity": "sha512-b7xaGIwdJlht8ZFCvMkpDN6uiSmnxxK56N2GDTMYPr2/gzvfdQN8rTfBsvVKmIVY/X7EM+/hJKEIbbHs9oA4tQ==", ++ "node_modules/@rolldown/binding-android-arm64": { ++ "version": "1.2.8", ++ "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.8.tgz", ++ "integrity": "sha512-dIYTWl9XprMUiQFoc55KUyk/oS8SKYH3zFl0LTR7RT0Xj4hgSVyuJcroH8JUu8RcpF8fTB6E0aOwCkZoYPcDSQ==", + "cpu": [ + "arm64" + ], +@@ -355,18 +363,18 @@ + "license": "MIT", + "optional": true, + "os": [ +- "darwin" ++ "android" + ], + "engines": { +- "node": ">=18" ++ "node": "^20.19.0 || >=22.12.0" + } + }, +- "node_modules/@esbuild/darwin-x64": { +- "version": "0.27.4", +- "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.27.4.tgz", +- "integrity": "sha512-sR+OiKLwd15nmCdqpXMnuJ9W2kpy0KigzqScqHI3Hqwr7IXxBp3Yva+yJwoqh7rE8V77tdoheRYataNKL4QrPw==", ++ "node_modules/@rolldown/binding-darwin-arm64": { ++ "version": "1.2.8", ++ "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.8.tgz", ++ "integrity": "sha512-PCSDQGXD2IyTEFrcgPyBM8jJuGmrbCMuoIOXdbEGVemruKACXoLQJrb+A45Z0L5t1RQkdfJprAYPkikbh7dzdA==", + "cpu": [ +- "x64" ++ "arm64" + ], + "dev": true, + "license": "MIT", +@@ -375,30 +383,30 @@ + "darwin" + ], + "engines": { +- "node": ">=18" ++ "node": "^20.19.0 || >=22.12.0" + } + }, +- "node_modules/@esbuild/freebsd-arm64": { +- "version": "0.27.4", +- "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.27.4.tgz", +- "integrity": "sha512-jnfpKe+p79tCnm4GVav68A7tUFeKQwQyLgESwEAUzyxk/TJr4QdGog9sqWNcUbr/bZt/O/HXouspuQDd9JxFSw==", ++ "node_modules/@rolldown/binding-darwin-x64": { ++ "version": "1.2.8", ++ "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.8.tgz", ++ "integrity": "sha512-Uk7lRsGhPFHVX/sAUC6D5H9Ol30dFHd6iquokll2th3LpdJ3F5CzQB+7DHn0Ri2mG+U7k2zXiPHDrwZenXhwSA==", + "cpu": [ +- "arm64" ++ "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ +- "freebsd" ++ "darwin" + ], + "engines": { +- "node": ">=18" ++ "node": "^20.19.0 || >=22.12.0" + } + }, +- "node_modules/@esbuild/freebsd-x64": { +- "version": "0.27.4", +- "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.27.4.tgz", +- "integrity": "sha512-2kb4ceA/CpfUrIcTUl1wrP/9ad9Atrp5J94Lq69w7UwOMolPIGrfLSvAKJp0RTvkPPyn6CIWrNy13kyLikZRZQ==", ++ "node_modules/@rolldown/binding-freebsd-x64": { ++ "version": "1.2.8", ++ "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.8.tgz", ++ "integrity": "sha512-DjszaTEVogPqA5bYzsEeqDCQxbcp2fexQwKcRspYji2yzR68fCf+e4fx6kBSRDwX5/brZaHw/hWS9+A/+/w9sQ==", + "cpu": [ + "x64" + ], +@@ -409,13 +417,13 @@ + "freebsd" + ], + "engines": { +- "node": ">=18" ++ "node": "^20.19.0 || >=22.12.0" + } + }, +- "node_modules/@esbuild/linux-arm": { +- "version": "0.27.4", +- "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.27.4.tgz", +- "integrity": "sha512-aBYgcIxX/wd5n2ys0yESGeYMGF+pv6g0DhZr3G1ZG4jMfruU9Tl1i2Z+Wnj9/KjGz1lTLCcorqE2viePZqj4Eg==", ++ "node_modules/@rolldown/binding-linux-arm-gnueabihf": { ++ "version": "1.2.8", ++ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.8.tgz", ++ "integrity": "sha512-zmwa7FTmdzB6aaEEuuls18H6Ap5JmJPSoPTuXixeJZV6tG40SyLkApQtz1g8ptZtiEKqj9OM0oNLPh1AgvE31Q==", + "cpu": [ + "arm" + ], +@@ -426,13 +434,13 @@ + "linux" + ], + "engines": { +- "node": ">=18" ++ "node": "^20.19.0 || >=22.12.0" + } + }, +- "node_modules/@esbuild/linux-arm64": { +- "version": "0.27.4", +- "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.27.4.tgz", +- "integrity": "sha512-7nQOttdzVGth1iz57kxg9uCz57dxQLHWxopL6mYuYthohPKEK0vU0C3O21CcBK6KDlkYVcnDXY099HcCDXd9dA==", ++ "node_modules/@rolldown/binding-linux-arm64-gnu": { ++ "version": "1.2.8", ++ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.8.tgz", ++ "integrity": "sha512-KdYQDPHwJVnbFwdTGMgxsI9SqblBlz6STGM+w1We/d5B8OWWidYH0MwkU/uA1wM5fIpO2MkOVxXrNzzuZhw9ew==", + "cpu": [ + "arm64" + ], +@@ -443,49 +451,15 @@ + "linux" + ], + "engines": { +- "node": ">=18" +- } +- }, +- "node_modules/@esbuild/linux-ia32": { +- "version": "0.27.4", +- "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.27.4.tgz", +- "integrity": "sha512-oPtixtAIzgvzYcKBQM/qZ3R+9TEUd1aNJQu0HhGyqtx6oS7qTpvjheIWBbes4+qu1bNlo2V4cbkISr8q6gRBFA==", +- "cpu": [ +- "ia32" +- ], +- "dev": true, +- "license": "MIT", +- "optional": true, +- "os": [ +- "linux" +- ], +- "engines": { +- "node": ">=18" +- } +- }, +- "node_modules/@esbuild/linux-loong64": { +- "version": "0.14.54", +- "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.14.54.tgz", +- "integrity": "sha512-bZBrLAIX1kpWelV0XemxBZllyRmM6vgFQQG2GdNb+r3Fkp0FOh1NJSvekXDs7jq70k4euu1cryLMfU+mTXlEpw==", +- "cpu": [ +- "loong64" +- ], +- "dev": true, +- "license": "MIT", +- "optional": true, +- "os": [ +- "linux" +- ], +- "engines": { +- "node": ">=12" ++ "node": "^20.19.0 || >=22.12.0" + } + }, +- "node_modules/@esbuild/linux-mips64el": { +- "version": "0.27.4", +- "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.27.4.tgz", +- "integrity": "sha512-1RdrWFFiiLIW7LQq9Q2NES+HiD4NyT8Itj9AUeCl0IVCA459WnPhREKgwrpaIfTOe+/2rdntisegiPWn/r/aAw==", ++ "node_modules/@rolldown/binding-linux-arm64-musl": { ++ "version": "1.2.8", ++ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.8.tgz", ++ "integrity": "sha512-jFJTifHnNPY+yzOoNZQfSIysrVyXzEQPhPnOUjmD1bcQGHH6s7c8cViKWar8YplQImE5N9JRqMCLrM2CdxOrZA==", + "cpu": [ +- "mips64el" ++ "arm64" + ], + "dev": true, + "license": "MIT", +@@ -494,13 +468,13 @@ + "linux" + ], + "engines": { +- "node": ">=18" ++ "node": "^20.19.0 || >=22.12.0" + } + }, +- "node_modules/@esbuild/linux-ppc64": { +- "version": "0.27.4", +- "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.27.4.tgz", +- "integrity": "sha512-tLCwNG47l3sd9lpfyx9LAGEGItCUeRCWeAx6x2Jmbav65nAwoPXfewtAdtbtit/pJFLUWOhpv0FpS6GQAmPrHA==", ++ "node_modules/@rolldown/binding-linux-ppc64-gnu": { ++ "version": "1.2.8", ++ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.8.tgz", ++ "integrity": "sha512-FhiOziBDWPBjbcmRzfLyIJnaP7AVMFXT7YCXPjXxj7wKU3vx24RjrCNN/zjvVa+N2vVoHJwCoUBvsrN/DG3zIA==", + "cpu": [ + "ppc64" + ], +@@ -511,30 +485,13 @@ + "linux" + ], + "engines": { +- "node": ">=18" +- } +- }, +- "node_modules/@esbuild/linux-riscv64": { +- "version": "0.27.4", +- "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.27.4.tgz", +- "integrity": "sha512-BnASypppbUWyqjd1KIpU4AUBiIhVr6YlHx/cnPgqEkNoVOhHg+YiSVxM1RLfiy4t9cAulbRGTNCKOcqHrEQLIw==", +- "cpu": [ +- "riscv64" +- ], +- "dev": true, +- "license": "MIT", +- "optional": true, +- "os": [ +- "linux" +- ], +- "engines": { +- "node": ">=18" ++ "node": "^20.19.0 || >=22.12.0" + } + }, +- "node_modules/@esbuild/linux-s390x": { +- "version": "0.27.4", +- "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.27.4.tgz", +- "integrity": "sha512-+eUqgb/Z7vxVLezG8bVB9SfBie89gMueS+I0xYh2tJdw3vqA/0ImZJ2ROeWwVJN59ihBeZ7Tu92dF/5dy5FttA==", ++ "node_modules/@rolldown/binding-linux-s390x-gnu": { ++ "version": "1.2.8", ++ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.8.tgz", ++ "integrity": "sha512-WnHfADMzOV2Y55wlx1hzzQnar/wDt/VdvWSD99r18Mz9ylNieIGOkRx3UV21h7m/eJvjySYJkO26VvGNFkwsIQ==", + "cpu": [ + "s390x" + ], +@@ -545,13 +502,13 @@ + "linux" + ], + "engines": { +- "node": ">=18" ++ "node": "^20.19.0 || >=22.12.0" + } + }, +- "node_modules/@esbuild/linux-x64": { +- "version": "0.27.4", +- "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.27.4.tgz", +- "integrity": "sha512-S5qOXrKV8BQEzJPVxAwnryi2+Iq5pB40gTEIT69BQONqR7JH1EPIcQ/Uiv9mCnn05jff9umq/5nqzxlqTOg9NA==", ++ "node_modules/@rolldown/binding-linux-x64-gnu": { ++ "version": "1.2.8", ++ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.8.tgz", ++ "integrity": "sha512-H9tRr5ibfXFVLxbPOseVewewFpl28zcEdjRDt2FTUZU7odxP0gEv1ki4/kGmcGOh78oRwZuuQllGLZ9zTJp84g==", + "cpu": [ + "x64" + ], +@@ -562,64 +519,13 @@ + "linux" + ], + "engines": { +- "node": ">=18" +- } +- }, +- "node_modules/@esbuild/netbsd-arm64": { +- "version": "0.27.4", +- "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.27.4.tgz", +- "integrity": "sha512-xHT8X4sb0GS8qTqiwzHqpY00C95DPAq7nAwX35Ie/s+LO9830hrMd3oX0ZMKLvy7vsonee73x0lmcdOVXFzd6Q==", +- "cpu": [ +- "arm64" +- ], +- "dev": true, +- "license": "MIT", +- "optional": true, +- "os": [ +- "netbsd" +- ], +- "engines": { +- "node": ">=18" +- } +- }, +- "node_modules/@esbuild/netbsd-x64": { +- "version": "0.27.4", +- "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.27.4.tgz", +- "integrity": "sha512-RugOvOdXfdyi5Tyv40kgQnI0byv66BFgAqjdgtAKqHoZTbTF2QqfQrFwa7cHEORJf6X2ht+l9ABLMP0dnKYsgg==", +- "cpu": [ +- "x64" +- ], +- "dev": true, +- "license": "MIT", +- "optional": true, +- "os": [ +- "netbsd" +- ], +- "engines": { +- "node": ">=18" +- } +- }, +- "node_modules/@esbuild/openbsd-arm64": { +- "version": "0.27.4", +- "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.27.4.tgz", +- "integrity": "sha512-2MyL3IAaTX+1/qP0O1SwskwcwCoOI4kV2IBX1xYnDDqthmq5ArrW94qSIKCAuRraMgPOmG0RDTA74mzYNQA9ow==", +- "cpu": [ +- "arm64" +- ], +- "dev": true, +- "license": "MIT", +- "optional": true, +- "os": [ +- "openbsd" +- ], +- "engines": { +- "node": ">=18" ++ "node": "^20.19.0 || >=22.12.0" + } + }, +- "node_modules/@esbuild/openbsd-x64": { +- "version": "0.27.4", +- "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.27.4.tgz", +- "integrity": "sha512-u8fg/jQ5aQDfsnIV6+KwLOf1CmJnfu1ShpwqdwC0uA7ZPwFws55Ngc12vBdeUdnuWoQYx/SOQLGDcdlfXhYmXQ==", ++ "node_modules/@rolldown/binding-linux-x64-musl": { ++ "version": "1.2.8", ++ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.8.tgz", ++ "integrity": "sha512-UefiqfM3D6IVNlZ8tSGs9+Ejjud2T+oxO0IHADU45Y+lyEjD2dVFyZHbkfX0LUb5Zugo/oIv1eCO/KVYhgYJYA==", + "cpu": [ + "x64" + ], +@@ -627,16 +533,16 @@ + "license": "MIT", + "optional": true, + "os": [ +- "openbsd" ++ "linux" + ], + "engines": { +- "node": ">=18" ++ "node": "^20.19.0 || >=22.12.0" + } + }, +- "node_modules/@esbuild/openharmony-arm64": { +- "version": "0.27.4", +- "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.27.4.tgz", +- "integrity": "sha512-JkTZrl6VbyO8lDQO3yv26nNr2RM2yZzNrNHEsj9bm6dOwwu9OYN28CjzZkH57bh4w0I2F7IodpQvUAEd1mbWXg==", ++ "node_modules/@rolldown/binding-openharmony-arm64": { ++ "version": "1.2.8", ++ "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.8.tgz", ++ "integrity": "sha512-637Ke4kWSy6rp9cxQ9gMOXlxPgIw/c1beASV4M//3+9I4uwBVOOl74G+e3zyU3u19U7RkRl/HuewixZ/Z6+Rjg==", + "cpu": [ + "arm64" + ], +@@ -647,30 +553,13 @@ + "openharmony" + ], + "engines": { +- "node": ">=18" +- } +- }, +- "node_modules/@esbuild/sunos-x64": { +- "version": "0.27.4", +- "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.27.4.tgz", +- "integrity": "sha512-/gOzgaewZJfeJTlsWhvUEmUG4tWEY2Spp5M20INYRg2ZKl9QPO3QEEgPeRtLjEWSW8FilRNacPOg8R1uaYkA6g==", +- "cpu": [ +- "x64" +- ], +- "dev": true, +- "license": "MIT", +- "optional": true, +- "os": [ +- "sunos" +- ], +- "engines": { +- "node": ">=18" ++ "node": "^20.19.0 || >=22.12.0" + } + }, +- "node_modules/@esbuild/win32-arm64": { +- "version": "0.27.4", +- "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.27.4.tgz", +- "integrity": "sha512-Z9SExBg2y32smoDQdf1HRwHRt6vAHLXcxD2uGgO/v2jK7Y718Ix4ndsbNMU/+1Qiem9OiOdaqitioZwxivhXYg==", ++ "node_modules/@rolldown/binding-win32-arm64-msvc": { ++ "version": "1.2.8", ++ "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.8.tgz", ++ "integrity": "sha512-xWBkPOF1Q9k/Gv1nQXnVdLxKu74jXppuOM4Z3mnypVUJJJwLsMl7hNJGRAUJoG8A5MgOI1ACKM+wBFxSJzKy4A==", + "cpu": [ + "arm64" + ], +@@ -681,30 +570,13 @@ + "win32" + ], + "engines": { +- "node": ">=18" +- } +- }, +- "node_modules/@esbuild/win32-ia32": { +- "version": "0.27.4", +- "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.27.4.tgz", +- "integrity": "sha512-DAyGLS0Jz5G5iixEbMHi5KdiApqHBWMGzTtMiJ72ZOLhbu/bzxgAe8Ue8CTS3n3HbIUHQz/L51yMdGMeoxXNJw==", +- "cpu": [ +- "ia32" +- ], +- "dev": true, +- "license": "MIT", +- "optional": true, +- "os": [ +- "win32" +- ], +- "engines": { +- "node": ">=18" ++ "node": "^20.19.0 || >=22.12.0" + } + }, +- "node_modules/@esbuild/win32-x64": { +- "version": "0.27.4", +- "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.27.4.tgz", +- "integrity": "sha512-+knoa0BDoeXgkNvvV1vvbZX4+hizelrkwmGJBdT17t8FNPwG2lKemmuMZlmaNQ3ws3DKKCxpb4zRZEIp3UxFCg==", ++ "node_modules/@rolldown/binding-win32-x64-msvc": { ++ "version": "1.2.8", ++ "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.8.tgz", ++ "integrity": "sha512-uz2ZvfgXbxqNwijjjbxrnvALwpyODDcgc1T1N8N3rf/DXKQmaFwmB4LX4yyjggpwN2obdQLb2rgirX5ffCWYng==", + "cpu": [ + "x64" + ], +@@ -715,390 +587,22 @@ + "win32" + ], + "engines": { +- "node": ">=18" +- } +- }, +- "node_modules/@floating-ui/core": { +- "version": "1.7.5", +- "resolved": "https://registry.npmjs.org/@floating-ui/core/-/core-1.7.5.tgz", +- "integrity": "sha512-1Ih4WTWyw0+lKyFMcBHGbb5U5FtuHJuujoyyr5zTaWS5EYMeT6Jb2AuDeftsCsEuchO+mM2ij5+q9crhydzLhQ==", +- "license": "MIT", +- "dependencies": { +- "@floating-ui/utils": "^0.2.11" +- } +- }, +- "node_modules/@floating-ui/dom": { +- "version": "1.7.6", +- "resolved": "https://registry.npmjs.org/@floating-ui/dom/-/dom-1.7.6.tgz", +- "integrity": "sha512-9gZSAI5XM36880PPMm//9dfiEngYoC6Am2izES1FF406YFsjvyBMmeJ2g4SAju3xWwtuynNRFL2s9hgxpLI5SQ==", +- "license": "MIT", +- "dependencies": { +- "@floating-ui/core": "^1.7.5", +- "@floating-ui/utils": "^0.2.11" ++ "node": "^20.19.0 || >=22.12.0" + } + }, +- "node_modules/@floating-ui/utils": { +- "version": "0.2.11", +- "resolved": "https://registry.npmjs.org/@floating-ui/utils/-/utils-0.2.11.tgz", +- "integrity": "sha512-RiB/yIh78pcIxl6lLMG0CgBXAZ2Y0eVHqMPYugu+9U0AeT6YBeiJpf7lbdJNIugFP5SIjwNRgo4DhR1Qxi26Gg==", +- "license": "MIT" +- }, +- "node_modules/@jridgewell/sourcemap-codec": { +- "version": "1.5.5", +- "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", +- "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==", ++ "node_modules/@rolldown/pluginutils": { ++ "version": "1.0.1", ++ "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.1.tgz", ++ "integrity": "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==", + "dev": true, + "license": "MIT" + }, +- "node_modules/@rollup/rollup-android-arm-eabi": { +- "version": "4.60.1", +- "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.60.1.tgz", +- "integrity": "sha512-d6FinEBLdIiK+1uACUttJKfgZREXrF0Qc2SmLII7W2AD8FfiZ9Wjd+rD/iRuf5s5dWrr1GgwXCvPqOuDquOowA==", +- "cpu": [ +- "arm" +- ], +- "dev": true, +- "license": "MIT", +- "optional": true, +- "os": [ +- "android" +- ] +- }, +- "node_modules/@rollup/rollup-android-arm64": { +- "version": "4.60.1", +- "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.60.1.tgz", +- "integrity": "sha512-YjG/EwIDvvYI1YvYbHvDz/BYHtkY4ygUIXHnTdLhG+hKIQFBiosfWiACWortsKPKU/+dUwQQCKQM3qrDe8c9BA==", +- "cpu": [ +- "arm64" +- ], +- "dev": true, +- "license": "MIT", +- "optional": true, +- "os": [ +- "android" +- ] +- }, +- "node_modules/@rollup/rollup-darwin-arm64": { +- "version": "4.60.1", +- "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.60.1.tgz", +- "integrity": "sha512-mjCpF7GmkRtSJwon+Rq1N8+pI+8l7w5g9Z3vWj4T7abguC4Czwi3Yu/pFaLvA3TTeMVjnu3ctigusqWUfjZzvw==", +- "cpu": [ +- "arm64" +- ], +- "dev": true, +- "license": "MIT", +- "optional": true, +- "os": [ +- "darwin" +- ] +- }, +- "node_modules/@rollup/rollup-darwin-x64": { +- "version": "4.60.1", +- "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.60.1.tgz", +- "integrity": "sha512-haZ7hJ1JT4e9hqkoT9R/19XW2QKqjfJVv+i5AGg57S+nLk9lQnJ1F/eZloRO3o9Scy9CM3wQ9l+dkXtcBgN5Ew==", +- "cpu": [ +- "x64" +- ], +- "dev": true, +- "license": "MIT", +- "optional": true, +- "os": [ +- "darwin" +- ] +- }, +- "node_modules/@rollup/rollup-freebsd-arm64": { +- "version": "4.60.1", +- "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.60.1.tgz", +- "integrity": "sha512-czw90wpQq3ZsAVBlinZjAYTKduOjTywlG7fEeWKUA7oCmpA8xdTkxZZlwNJKWqILlq0wehoZcJYfBvOyhPTQ6w==", +- "cpu": [ +- "arm64" +- ], +- "dev": true, +- "license": "MIT", +- "optional": true, +- "os": [ +- "freebsd" +- ] +- }, +- "node_modules/@rollup/rollup-freebsd-x64": { +- "version": "4.60.1", +- "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.60.1.tgz", +- "integrity": "sha512-KVB2rqsxTHuBtfOeySEyzEOB7ltlB/ux38iu2rBQzkjbwRVlkhAGIEDiiYnO2kFOkJp+Z7pUXKyrRRFuFUKt+g==", +- "cpu": [ +- "x64" +- ], +- "dev": true, +- "license": "MIT", +- "optional": true, +- "os": [ +- "freebsd" +- ] +- }, +- "node_modules/@rollup/rollup-linux-arm-gnueabihf": { +- "version": "4.60.1", +- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.60.1.tgz", +- "integrity": "sha512-L+34Qqil+v5uC0zEubW7uByo78WOCIrBvci69E7sFASRl0X7b/MB6Cqd1lky/CtcSVTydWa2WZwFuWexjS5o6g==", +- "cpu": [ +- "arm" +- ], +- "dev": true, +- "license": "MIT", +- "optional": true, +- "os": [ +- "linux" +- ] +- }, +- "node_modules/@rollup/rollup-linux-arm-musleabihf": { +- "version": "4.60.1", +- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.60.1.tgz", +- "integrity": "sha512-n83O8rt4v34hgFzlkb1ycniJh7IR5RCIqt6mz1VRJD6pmhRi0CXdmfnLu9dIUS6buzh60IvACM842Ffb3xd6Gg==", +- "cpu": [ +- "arm" +- ], +- "dev": true, +- "license": "MIT", +- "optional": true, +- "os": [ +- "linux" +- ] +- }, +- "node_modules/@rollup/rollup-linux-arm64-gnu": { +- "version": "4.60.1", +- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.60.1.tgz", +- "integrity": "sha512-Nql7sTeAzhTAja3QXeAI48+/+GjBJ+QmAH13snn0AJSNL50JsDqotyudHyMbO2RbJkskbMbFJfIJKWA6R1LCJQ==", +- "cpu": [ +- "arm64" +- ], +- "dev": true, +- "license": "MIT", +- "optional": true, +- "os": [ +- "linux" +- ] +- }, +- "node_modules/@rollup/rollup-linux-arm64-musl": { +- "version": "4.60.1", +- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.60.1.tgz", +- "integrity": "sha512-+pUymDhd0ys9GcKZPPWlFiZ67sTWV5UU6zOJat02M1+PiuSGDziyRuI/pPue3hoUwm2uGfxdL+trT6Z9rxnlMA==", +- "cpu": [ +- "arm64" +- ], ++ "node_modules/@standard-schema/spec": { ++ "version": "1.1.0", ++ "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz", ++ "integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==", + "dev": true, +- "license": "MIT", +- "optional": true, +- "os": [ +- "linux" +- ] +- }, +- "node_modules/@rollup/rollup-linux-loong64-gnu": { +- "version": "4.60.1", +- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.60.1.tgz", +- "integrity": "sha512-VSvgvQeIcsEvY4bKDHEDWcpW4Yw7BtlKG1GUT4FzBUlEKQK0rWHYBqQt6Fm2taXS+1bXvJT6kICu5ZwqKCnvlQ==", +- "cpu": [ +- "loong64" +- ], +- "dev": true, +- "license": "MIT", +- "optional": true, +- "os": [ +- "linux" +- ] +- }, +- "node_modules/@rollup/rollup-linux-loong64-musl": { +- "version": "4.60.1", +- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.60.1.tgz", +- "integrity": "sha512-4LqhUomJqwe641gsPp6xLfhqWMbQV04KtPp7/dIp0nzPxAkNY1AbwL5W0MQpcalLYk07vaW9Kp1PBhdpZYYcEw==", +- "cpu": [ +- "loong64" +- ], +- "dev": true, +- "license": "MIT", +- "optional": true, +- "os": [ +- "linux" +- ] +- }, +- "node_modules/@rollup/rollup-linux-ppc64-gnu": { +- "version": "4.60.1", +- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.60.1.tgz", +- "integrity": "sha512-tLQQ9aPvkBxOc/EUT6j3pyeMD6Hb8QF2BTBnCQWP/uu1lhc9AIrIjKnLYMEroIz/JvtGYgI9dF3AxHZNaEH0rw==", +- "cpu": [ +- "ppc64" +- ], +- "dev": true, +- "license": "MIT", +- "optional": true, +- "os": [ +- "linux" +- ] +- }, +- "node_modules/@rollup/rollup-linux-ppc64-musl": { +- "version": "4.60.1", +- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.60.1.tgz", +- "integrity": "sha512-RMxFhJwc9fSXP6PqmAz4cbv3kAyvD1etJFjTx4ONqFP9DkTkXsAMU4v3Vyc5BgzC+anz7nS/9tp4obsKfqkDHg==", +- "cpu": [ +- "ppc64" +- ], +- "dev": true, +- "license": "MIT", +- "optional": true, +- "os": [ +- "linux" +- ] +- }, +- "node_modules/@rollup/rollup-linux-riscv64-gnu": { +- "version": "4.60.1", +- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.60.1.tgz", +- "integrity": "sha512-QKgFl+Yc1eEk6MmOBfRHYF6lTxiiiV3/z/BRrbSiW2I7AFTXoBFvdMEyglohPj//2mZS4hDOqeB0H1ACh3sBbg==", +- "cpu": [ +- "riscv64" +- ], +- "dev": true, +- "license": "MIT", +- "optional": true, +- "os": [ +- "linux" +- ] +- }, +- "node_modules/@rollup/rollup-linux-riscv64-musl": { +- "version": "4.60.1", +- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.60.1.tgz", +- "integrity": "sha512-RAjXjP/8c6ZtzatZcA1RaQr6O1TRhzC+adn8YZDnChliZHviqIjmvFwHcxi4JKPSDAt6Uhf/7vqcBzQJy0PDJg==", +- "cpu": [ +- "riscv64" +- ], +- "dev": true, +- "license": "MIT", +- "optional": true, +- "os": [ +- "linux" +- ] +- }, +- "node_modules/@rollup/rollup-linux-s390x-gnu": { +- "version": "4.60.1", +- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.60.1.tgz", +- "integrity": "sha512-wcuocpaOlaL1COBYiA89O6yfjlp3RwKDeTIA0hM7OpmhR1Bjo9j31G1uQVpDlTvwxGn2nQs65fBFL5UFd76FcQ==", +- "cpu": [ +- "s390x" +- ], +- "dev": true, +- "license": "MIT", +- "optional": true, +- "os": [ +- "linux" +- ] +- }, +- "node_modules/@rollup/rollup-linux-x64-gnu": { +- "version": "4.60.1", +- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.60.1.tgz", +- "integrity": "sha512-77PpsFQUCOiZR9+LQEFg9GClyfkNXj1MP6wRnzYs0EeWbPcHs02AXu4xuUbM1zhwn3wqaizle3AEYg5aeoohhg==", +- "cpu": [ +- "x64" +- ], +- "dev": true, +- "license": "MIT", +- "optional": true, +- "os": [ +- "linux" +- ] +- }, +- "node_modules/@rollup/rollup-linux-x64-musl": { +- "version": "4.60.1", +- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.60.1.tgz", +- "integrity": "sha512-5cIATbk5vynAjqqmyBjlciMJl1+R/CwX9oLk/EyiFXDWd95KpHdrOJT//rnUl4cUcskrd0jCCw3wpZnhIHdD9w==", +- "cpu": [ +- "x64" +- ], +- "dev": true, +- "license": "MIT", +- "optional": true, +- "os": [ +- "linux" +- ] +- }, +- "node_modules/@rollup/rollup-openbsd-x64": { +- "version": "4.60.1", +- "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.60.1.tgz", +- "integrity": "sha512-cl0w09WsCi17mcmWqqglez9Gk8isgeWvoUZ3WiJFYSR3zjBQc2J5/ihSjpl+VLjPqjQ/1hJRcqBfLjssREQILw==", +- "cpu": [ +- "x64" +- ], +- "dev": true, +- "license": "MIT", +- "optional": true, +- "os": [ +- "openbsd" +- ] +- }, +- "node_modules/@rollup/rollup-openharmony-arm64": { +- "version": "4.60.1", +- "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.60.1.tgz", +- "integrity": "sha512-4Cv23ZrONRbNtbZa37mLSueXUCtN7MXccChtKpUnQNgF010rjrjfHx3QxkS2PI7LqGT5xXyYs1a7LbzAwT0iCA==", +- "cpu": [ +- "arm64" +- ], +- "dev": true, +- "license": "MIT", +- "optional": true, +- "os": [ +- "openharmony" +- ] +- }, +- "node_modules/@rollup/rollup-win32-arm64-msvc": { +- "version": "4.60.1", +- "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.60.1.tgz", +- "integrity": "sha512-i1okWYkA4FJICtr7KpYzFpRTHgy5jdDbZiWfvny21iIKky5YExiDXP+zbXzm3dUcFpkEeYNHgQ5fuG236JPq0g==", +- "cpu": [ +- "arm64" +- ], +- "dev": true, +- "license": "MIT", +- "optional": true, +- "os": [ +- "win32" +- ] +- }, +- "node_modules/@rollup/rollup-win32-ia32-msvc": { +- "version": "4.60.1", +- "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.60.1.tgz", +- "integrity": "sha512-u09m3CuwLzShA0EYKMNiFgcjjzwqtUMLmuCJLeZWjjOYA3IT2Di09KaxGBTP9xVztWyIWjVdsB2E9goMjZvTQg==", +- "cpu": [ +- "ia32" +- ], +- "dev": true, +- "license": "MIT", +- "optional": true, +- "os": [ +- "win32" +- ] +- }, +- "node_modules/@rollup/rollup-win32-x64-gnu": { +- "version": "4.60.1", +- "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.60.1.tgz", +- "integrity": "sha512-k+600V9Zl1CM7eZxJgMyTUzmrmhB/0XZnF4pRypKAlAgxmedUA+1v9R+XOFv56W4SlHEzfeMtzujLJD22Uz5zg==", +- "cpu": [ +- "x64" +- ], +- "dev": true, +- "license": "MIT", +- "optional": true, +- "os": [ +- "win32" +- ] +- }, +- "node_modules/@rollup/rollup-win32-x64-msvc": { +- "version": "4.60.1", +- "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.60.1.tgz", +- "integrity": "sha512-lWMnixq/QzxyhTV6NjQJ4SFo1J6PvOX8vUx5Wb4bBPsEb+8xZ89Bz6kOXpfXj9ak9AHTQVQzlgzBEc1SyM27xQ==", +- "cpu": [ +- "x64" +- ], +- "dev": true, +- "license": "MIT", +- "optional": true, +- "os": [ +- "win32" +- ] ++ "license": "MIT" + }, + "node_modules/@types/chai": { + "version": "5.2.3", +@@ -1119,46 +623,47 @@ + "license": "MIT" + }, + "node_modules/@types/estree": { +- "version": "1.0.8", +- "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz", +- "integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==", ++ "version": "1.0.9", ++ "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz", ++ "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@vitest/expect": { +- "version": "3.2.4", +- "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-3.2.4.tgz", +- "integrity": "sha512-Io0yyORnB6sikFlt8QW5K7slY4OjqNX9jmJQ02QDda8lyM6B5oNgVWoSoKPac8/kgnCUzuHQKrSLtu/uOqqrig==", ++ "version": "4.1.11", ++ "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.11.tgz", ++ "integrity": "sha512-VX2x5vNJXET47KAFzwERI+KRMtTTCSWTfSMKsW7JsUsXV4psq++e3DvZpuTDOpHcxytiDs6p2nhVb2tVDiiUYw==", + "dev": true, + "license": "MIT", + "dependencies": { ++ "@standard-schema/spec": "^1.1.0", + "@types/chai": "^5.2.2", +- "@vitest/spy": "3.2.4", +- "@vitest/utils": "3.2.4", +- "chai": "^5.2.0", +- "tinyrainbow": "^2.0.0" ++ "@vitest/spy": "4.1.11", ++ "@vitest/utils": "4.1.11", ++ "chai": "^6.2.2", ++ "tinyrainbow": "^3.1.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/mocker": { +- "version": "3.2.4", +- "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-3.2.4.tgz", +- "integrity": "sha512-46ryTE9RZO/rfDd7pEqFl7etuyzekzEhUbTW3BvmeO/BcCMEgq59BKhek3dXDWgAj4oMK6OZi+vRr1wPW6qjEQ==", ++ "version": "4.1.11", ++ "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-4.1.11.tgz", ++ "integrity": "sha512-2XJVD55d1o5AZous5CCGKS74g/riOj9odEt2bQpCVZeblHyHdnMeFl4jl0XjU21stf4mbjUkew2eXQZt65g5CQ==", + "dev": true, + "license": "MIT", + "dependencies": { +- "@vitest/spy": "3.2.4", ++ "@vitest/spy": "4.1.11", + "estree-walker": "^3.0.3", +- "magic-string": "^0.30.17" ++ "magic-string": "^0.30.21" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "msw": "^2.4.9", +- "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0" ++ "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "msw": { +@@ -1170,42 +675,42 @@ + } + }, + "node_modules/@vitest/pretty-format": { +- "version": "3.2.4", +- "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-3.2.4.tgz", +- "integrity": "sha512-IVNZik8IVRJRTr9fxlitMKeJeXFFFN0JaB9PHPGQ8NKQbGpfjlTx9zO4RefN8gp7eqjNy8nyK3NZmBzOPeIxtA==", ++ "version": "4.1.11", ++ "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-4.1.11.tgz", ++ "integrity": "sha512-yiZzPbGTS9Sr/JpFl8zHrcIkAofNbFV6k21vIgQN/cY/oxZeXhJv5sc/MBJ5jFKWmWs+oJHw0UXLZjmf931+Vw==", + "dev": true, + "license": "MIT", + "dependencies": { +- "tinyrainbow": "^2.0.0" ++ "tinyrainbow": "^3.1.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/runner": { +- "version": "3.2.4", +- "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-3.2.4.tgz", +- "integrity": "sha512-oukfKT9Mk41LreEW09vt45f8wx7DordoWUZMYdY/cyAk7w5TWkTRCNZYF7sX7n2wB7jyGAl74OxgwhPgKaqDMQ==", ++ "version": "4.1.11", ++ "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-4.1.11.tgz", ++ "integrity": "sha512-LztvUgdwMNJMIkj3hQnnxiC2Xy1zNxq928W/xhjCLaNCzqTZOudjwbQf6v9IntZGPw132i2Lq2rgTRZHD3JHNw==", + "dev": true, + "license": "MIT", + "dependencies": { +- "@vitest/utils": "3.2.4", +- "pathe": "^2.0.3", +- "strip-literal": "^3.0.0" ++ "@vitest/utils": "4.1.11", ++ "pathe": "^2.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/snapshot": { +- "version": "3.2.4", +- "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-3.2.4.tgz", +- "integrity": "sha512-dEYtS7qQP2CjU27QBC5oUOxLE/v5eLkGqPE0ZKEIDGMs4vKWe7IjgLOeauHsR0D5YuuycGRO5oSRXnwnmA78fQ==", ++ "version": "4.1.11", ++ "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-4.1.11.tgz", ++ "integrity": "sha512-pN7ikn1ON7h8ee4gIAp4AzyK+zBtJPzVbqOgu5LCEh4VaJVbPQcgYQYJIMGQPXVeJJq1fnfazis7a5pFNPahog==", + "dev": true, + "license": "MIT", + "dependencies": { +- "@vitest/pretty-format": "3.2.4", +- "magic-string": "^0.30.17", ++ "@vitest/pretty-format": "4.1.11", ++ "@vitest/utils": "4.1.11", ++ "magic-string": "^0.30.21", + "pathe": "^2.0.3" + }, + "funding": { +@@ -1213,28 +718,25 @@ + } + }, + "node_modules/@vitest/spy": { +- "version": "3.2.4", +- "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-3.2.4.tgz", +- "integrity": "sha512-vAfasCOe6AIK70iP5UD11Ac4siNUNJ9i/9PZ3NKx07sG6sUxeag1LWdNrMWeKKYBLlzuK+Gn65Yd5nyL6ds+nw==", ++ "version": "4.1.11", ++ "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-4.1.11.tgz", ++ "integrity": "sha512-apNa/prQy2qCeywhnixOHPRCgGNhvg7T4Dapfl1GahLp/R+uhBm5cPyFoNVyqsNd2h1nJxL6BqqdIjiABL60YA==", + "dev": true, + "license": "MIT", +- "dependencies": { +- "tinyspy": "^4.0.3" +- }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/utils": { +- "version": "3.2.4", +- "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-3.2.4.tgz", +- "integrity": "sha512-fB2V0JFrQSMsCo9HiSq3Ezpdv4iYaXRG1Sx8edX3MwxfyNn83mKiGzOcH+Fkxt4MHxr3y42fQi1oeAInqgX2QA==", ++ "version": "4.1.11", ++ "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-4.1.11.tgz", ++ "integrity": "sha512-zTCVGpyFsGWBhllOyKlTw/vnr6D9qxsfSDyfbyZmTyjHw5N/VuvzHpHoQjm2ZJzn4RJgx5w4r7V0er69CmLgPQ==", + "dev": true, + "license": "MIT", + "dependencies": { +- "@vitest/pretty-format": "3.2.4", +- "loupe": "^3.1.4", +- "tinyrainbow": "^2.0.0" ++ "@vitest/pretty-format": "4.1.11", ++ "convert-source-map": "^2.0.0", ++ "tinyrainbow": "^3.1.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" +@@ -1307,42 +809,22 @@ + "node": ">= 10.16.0" + } + }, +- "node_modules/cac": { +- "version": "6.7.14", +- "resolved": "https://registry.npmjs.org/cac/-/cac-6.7.14.tgz", +- "integrity": "sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==", +- "dev": true, +- "license": "MIT", +- "engines": { +- "node": ">=8" +- } +- }, + "node_modules/chai": { +- "version": "5.3.3", +- "resolved": "https://registry.npmjs.org/chai/-/chai-5.3.3.tgz", +- "integrity": "sha512-4zNhdJD/iOjSH0A05ea+Ke6MU5mmpQcbQsSOkgdaUMJ9zTlDTD/GYlwohmIE2u0gaxHYiVHEn1Fw9mZ/ktJWgw==", ++ "version": "6.2.2", ++ "resolved": "https://registry.npmjs.org/chai/-/chai-6.2.2.tgz", ++ "integrity": "sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==", + "dev": true, + "license": "MIT", +- "dependencies": { +- "assertion-error": "^2.0.1", +- "check-error": "^2.1.1", +- "deep-eql": "^5.0.1", +- "loupe": "^3.1.0", +- "pathval": "^2.0.0" +- }, + "engines": { + "node": ">=18" + } + }, +- "node_modules/check-error": { +- "version": "2.1.3", +- "resolved": "https://registry.npmjs.org/check-error/-/check-error-2.1.3.tgz", +- "integrity": "sha512-PAJdDJusoxnwm1VwW07VWwUN1sl7smmC3OKggvndJFadxxDRyFJBX/ggnu/KE4kQAB7a3Dp8f/YXC1FlUprWmA==", ++ "node_modules/convert-source-map": { ++ "version": "2.0.0", ++ "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", ++ "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", + "dev": true, +- "license": "MIT", +- "engines": { +- "node": ">= 16" +- } ++ "license": "MIT" + }, + "node_modules/css-tree": { + "version": "3.2.1", +@@ -1423,14 +905,14 @@ + "dev": true, + "license": "MIT" + }, +- "node_modules/deep-eql": { +- "version": "5.0.2", +- "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-5.0.2.tgz", +- "integrity": "sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q==", ++ "node_modules/detect-libc": { ++ "version": "2.1.2", ++ "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", ++ "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "dev": true, +- "license": "MIT", ++ "license": "Apache-2.0", + "engines": { +- "node": ">=6" ++ "node": ">=8" + } + }, + "node_modules/duplexer": { +@@ -1453,9 +935,9 @@ + } + }, + "node_modules/es-module-lexer": { +- "version": "1.7.0", +- "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-1.7.0.tgz", +- "integrity": "sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==", ++ "version": "2.3.2", ++ "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.2.tgz", ++ "integrity": "sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==", + "dev": true, + "license": "MIT" + }, +@@ -1959,13 +1441,6 @@ + "dev": true, + "license": "MIT" + }, +- "node_modules/js-tokens": { +- "version": "9.0.1", +- "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-9.0.1.tgz", +- "integrity": "sha512-mxa9E9ITFOt0ban3j6L5MpjwegGz6lBQmM1IJkWeBZGcMxto50+eWdjC/52xDbS2vy0k7vIMK0Fe2wfL9OQSpQ==", +- "dev": true, +- "license": "MIT" +- }, + "node_modules/jsdom": { + "version": "27.0.0", + "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-27.0.0.tgz", +@@ -2006,12 +1481,266 @@ + } + } + }, +- "node_modules/loupe": { +- "version": "3.2.1", +- "resolved": "https://registry.npmjs.org/loupe/-/loupe-3.2.1.tgz", +- "integrity": "sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ==", ++ "node_modules/lightningcss": { ++ "version": "1.33.0", ++ "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz", ++ "integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==", + "dev": true, +- "license": "MIT" ++ "license": "MPL-2.0", ++ "dependencies": { ++ "detect-libc": "^2.0.3" ++ }, ++ "engines": { ++ "node": ">= 12.0.0" ++ }, ++ "funding": { ++ "type": "opencollective", ++ "url": "https://opencollective.com/parcel" ++ }, ++ "optionalDependencies": { ++ "lightningcss-android-arm64": "1.33.0", ++ "lightningcss-darwin-arm64": "1.33.0", ++ "lightningcss-darwin-x64": "1.33.0", ++ "lightningcss-freebsd-x64": "1.33.0", ++ "lightningcss-linux-arm-gnueabihf": "1.33.0", ++ "lightningcss-linux-arm64-gnu": "1.33.0", ++ "lightningcss-linux-arm64-musl": "1.33.0", ++ "lightningcss-linux-x64-gnu": "1.33.0", ++ "lightningcss-linux-x64-musl": "1.33.0", ++ "lightningcss-win32-arm64-msvc": "1.33.0", ++ "lightningcss-win32-x64-msvc": "1.33.0" ++ } ++ }, ++ "node_modules/lightningcss-android-arm64": { ++ "version": "1.33.0", ++ "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.33.0.tgz", ++ "integrity": "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==", ++ "cpu": [ ++ "arm64" ++ ], ++ "dev": true, ++ "license": "MPL-2.0", ++ "optional": true, ++ "os": [ ++ "android" ++ ], ++ "engines": { ++ "node": ">= 12.0.0" ++ }, ++ "funding": { ++ "type": "opencollective", ++ "url": "https://opencollective.com/parcel" ++ } ++ }, ++ "node_modules/lightningcss-darwin-arm64": { ++ "version": "1.33.0", ++ "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.33.0.tgz", ++ "integrity": "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==", ++ "cpu": [ ++ "arm64" ++ ], ++ "dev": true, ++ "license": "MPL-2.0", ++ "optional": true, ++ "os": [ ++ "darwin" ++ ], ++ "engines": { ++ "node": ">= 12.0.0" ++ }, ++ "funding": { ++ "type": "opencollective", ++ "url": "https://opencollective.com/parcel" ++ } ++ }, ++ "node_modules/lightningcss-darwin-x64": { ++ "version": "1.33.0", ++ "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.33.0.tgz", ++ "integrity": "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==", ++ "cpu": [ ++ "x64" ++ ], ++ "dev": true, ++ "license": "MPL-2.0", ++ "optional": true, ++ "os": [ ++ "darwin" ++ ], ++ "engines": { ++ "node": ">= 12.0.0" ++ }, ++ "funding": { ++ "type": "opencollective", ++ "url": "https://opencollective.com/parcel" ++ } ++ }, ++ "node_modules/lightningcss-freebsd-x64": { ++ "version": "1.33.0", ++ "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.33.0.tgz", ++ "integrity": "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==", ++ "cpu": [ ++ "x64" ++ ], ++ "dev": true, ++ "license": "MPL-2.0", ++ "optional": true, ++ "os": [ ++ "freebsd" ++ ], ++ "engines": { ++ "node": ">= 12.0.0" ++ }, ++ "funding": { ++ "type": "opencollective", ++ "url": "https://opencollective.com/parcel" ++ } ++ }, ++ "node_modules/lightningcss-linux-arm-gnueabihf": { ++ "version": "1.33.0", ++ "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.33.0.tgz", ++ "integrity": "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==", ++ "cpu": [ ++ "arm" ++ ], ++ "dev": true, ++ "license": "MPL-2.0", ++ "optional": true, ++ "os": [ ++ "linux" ++ ], ++ "engines": { ++ "node": ">= 12.0.0" ++ }, ++ "funding": { ++ "type": "opencollective", ++ "url": "https://opencollective.com/parcel" ++ } ++ }, ++ "node_modules/lightningcss-linux-arm64-gnu": { ++ "version": "1.33.0", ++ "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.33.0.tgz", ++ "integrity": "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==", ++ "cpu": [ ++ "arm64" ++ ], ++ "dev": true, ++ "license": "MPL-2.0", ++ "optional": true, ++ "os": [ ++ "linux" ++ ], ++ "engines": { ++ "node": ">= 12.0.0" ++ }, ++ "funding": { ++ "type": "opencollective", ++ "url": "https://opencollective.com/parcel" ++ } ++ }, ++ "node_modules/lightningcss-linux-arm64-musl": { ++ "version": "1.33.0", ++ "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.33.0.tgz", ++ "integrity": "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==", ++ "cpu": [ ++ "arm64" ++ ], ++ "dev": true, ++ "license": "MPL-2.0", ++ "optional": true, ++ "os": [ ++ "linux" ++ ], ++ "engines": { ++ "node": ">= 12.0.0" ++ }, ++ "funding": { ++ "type": "opencollective", ++ "url": "https://opencollective.com/parcel" ++ } ++ }, ++ "node_modules/lightningcss-linux-x64-gnu": { ++ "version": "1.33.0", ++ "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.33.0.tgz", ++ "integrity": "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==", ++ "cpu": [ ++ "x64" ++ ], ++ "dev": true, ++ "license": "MPL-2.0", ++ "optional": true, ++ "os": [ ++ "linux" ++ ], ++ "engines": { ++ "node": ">= 12.0.0" ++ }, ++ "funding": { ++ "type": "opencollective", ++ "url": "https://opencollective.com/parcel" ++ } ++ }, ++ "node_modules/lightningcss-linux-x64-musl": { ++ "version": "1.33.0", ++ "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.33.0.tgz", ++ "integrity": "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==", ++ "cpu": [ ++ "x64" ++ ], ++ "dev": true, ++ "license": "MPL-2.0", ++ "optional": true, ++ "os": [ ++ "linux" ++ ], ++ "engines": { ++ "node": ">= 12.0.0" ++ }, ++ "funding": { ++ "type": "opencollective", ++ "url": "https://opencollective.com/parcel" ++ } ++ }, ++ "node_modules/lightningcss-win32-arm64-msvc": { ++ "version": "1.33.0", ++ "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.33.0.tgz", ++ "integrity": "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==", ++ "cpu": [ ++ "arm64" ++ ], ++ "dev": true, ++ "license": "MPL-2.0", ++ "optional": true, ++ "os": [ ++ "win32" ++ ], ++ "engines": { ++ "node": ">= 12.0.0" ++ }, ++ "funding": { ++ "type": "opencollective", ++ "url": "https://opencollective.com/parcel" ++ } ++ }, ++ "node_modules/lightningcss-win32-x64-msvc": { ++ "version": "1.33.0", ++ "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.33.0.tgz", ++ "integrity": "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==", ++ "cpu": [ ++ "x64" ++ ], ++ "dev": true, ++ "license": "MPL-2.0", ++ "optional": true, ++ "os": [ ++ "win32" ++ ], ++ "engines": { ++ "node": ">= 12.0.0" ++ }, ++ "funding": { ++ "type": "opencollective", ++ "url": "https://opencollective.com/parcel" ++ } + }, + "node_modules/lru-cache": { + "version": "11.2.7", +@@ -2072,6 +1801,20 @@ + "integrity": "sha512-I19aIingLgR1fmhftnbWWO3dXc0hSxqHQHQb3H8m+K3TnEn/iSeTZZOyvKXWqQESMwuUVnatlCnZdLBZZt2VSA==", + "license": "MIT" + }, ++ "node_modules/obug": { ++ "version": "2.2.1", ++ "resolved": "https://registry.npmjs.org/obug/-/obug-2.2.1.tgz", ++ "integrity": "sha512-XrsrhT5sybtKI6wakr2SPOlGZWWYbUXZ7a0jT8/QOeAPau+1X/bSegNe5YR75oJmEZQbKningirmGOEJCIk61Q==", ++ "dev": true, ++ "funding": [ ++ "https://github.com/sponsors/sxzz", ++ "https://opencollective.com/debug" ++ ], ++ "license": "MIT", ++ "engines": { ++ "node": ">=12.20.0" ++ } ++ }, + "node_modules/parse5": { + "version": "7.3.0", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-7.3.0.tgz", +@@ -2092,16 +1835,6 @@ + "dev": true, + "license": "MIT" + }, +- "node_modules/pathval": { +- "version": "2.0.1", +- "resolved": "https://registry.npmjs.org/pathval/-/pathval-2.0.1.tgz", +- "integrity": "sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ==", +- "dev": true, +- "license": "MIT", +- "engines": { +- "node": ">= 14.16" +- } +- }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", +@@ -2110,9 +1843,9 @@ + "license": "ISC" + }, + "node_modules/picomatch": { +- "version": "4.0.4", +- "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz", +- "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==", ++ "version": "4.0.7", ++ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", ++ "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", + "dev": true, + "license": "MIT", + "engines": { +@@ -2123,9 +1856,9 @@ + } + }, + "node_modules/postcss": { +- "version": "8.5.26", +- "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.26.tgz", +- "integrity": "sha512-u82N74LFzG8ca+dD8puPnplTXoGH4fTPpVGuIbt36G3qvNlkvfD0lEAZSxaly3KX8TS/L1A1gsCEmvKmBcVbkQ==", ++ "version": "8.5.28", ++ "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.28.tgz", ++ "integrity": "sha512-RRuzqDtt5Y9h3quz5hWhK+TPnsmVs6WwSU6LkJMeY4HstUEDuYTG8UJSdawMRzmzAtV+KEoG8N3Qg2qLy5vM/A==", + "dev": true, + "funding": [ + { +@@ -2143,7 +1876,7 @@ + ], + "license": "MIT", + "dependencies": { +- "nanoid": "^3.3.17", ++ "nanoid": "^3.3.18", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.1" + }, +@@ -2171,49 +1904,38 @@ + "node": ">=0.10.0" + } + }, +- "node_modules/rollup": { +- "version": "4.60.1", +- "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.60.1.tgz", +- "integrity": "sha512-VmtB2rFU/GroZ4oL8+ZqXgSA38O6GR8KSIvWmEFv63pQ0G6KaBH9s07PO8XTXP4vI+3UJUEypOfjkGfmSBBR0w==", ++ "node_modules/rolldown": { ++ "version": "1.2.8", ++ "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.8.tgz", ++ "integrity": "sha512-Z67nTmhZe7anqnM/EjI392w5i/ANUinjip7QYsOyN37oayduxt3ksdX0hf5OOamkAd53BiIHfbfSzfUmzKFQqQ==", + "dev": true, + "license": "MIT", + "dependencies": { +- "@types/estree": "1.0.8" ++ "@oxc-project/types": "=0.149.0", ++ "@rolldown/pluginutils": "^1.0.0" + }, + "bin": { +- "rollup": "dist/bin/rollup" ++ "rolldown": "bin/cli.mjs" + }, + "engines": { +- "node": ">=18.0.0", +- "npm": ">=8.0.0" ++ "node": "^20.19.0 || >=22.12.0" + }, + "optionalDependencies": { +- "@rollup/rollup-android-arm-eabi": "4.60.1", +- "@rollup/rollup-android-arm64": "4.60.1", +- "@rollup/rollup-darwin-arm64": "4.60.1", +- "@rollup/rollup-darwin-x64": "4.60.1", +- "@rollup/rollup-freebsd-arm64": "4.60.1", +- "@rollup/rollup-freebsd-x64": "4.60.1", +- "@rollup/rollup-linux-arm-gnueabihf": "4.60.1", +- "@rollup/rollup-linux-arm-musleabihf": "4.60.1", +- "@rollup/rollup-linux-arm64-gnu": "4.60.1", +- "@rollup/rollup-linux-arm64-musl": "4.60.1", +- "@rollup/rollup-linux-loong64-gnu": "4.60.1", +- "@rollup/rollup-linux-loong64-musl": "4.60.1", +- "@rollup/rollup-linux-ppc64-gnu": "4.60.1", +- "@rollup/rollup-linux-ppc64-musl": "4.60.1", +- "@rollup/rollup-linux-riscv64-gnu": "4.60.1", +- "@rollup/rollup-linux-riscv64-musl": "4.60.1", +- "@rollup/rollup-linux-s390x-gnu": "4.60.1", +- "@rollup/rollup-linux-x64-gnu": "4.60.1", +- "@rollup/rollup-linux-x64-musl": "4.60.1", +- "@rollup/rollup-openbsd-x64": "4.60.1", +- "@rollup/rollup-openharmony-arm64": "4.60.1", +- "@rollup/rollup-win32-arm64-msvc": "4.60.1", +- "@rollup/rollup-win32-ia32-msvc": "4.60.1", +- "@rollup/rollup-win32-x64-gnu": "4.60.1", +- "@rollup/rollup-win32-x64-msvc": "4.60.1", +- "fsevents": "~2.3.2" ++ "@rolldown/binding-android-arm-eabi": "1.2.8", ++ "@rolldown/binding-android-arm64": "1.2.8", ++ "@rolldown/binding-darwin-arm64": "1.2.8", ++ "@rolldown/binding-darwin-x64": "1.2.8", ++ "@rolldown/binding-freebsd-x64": "1.2.8", ++ "@rolldown/binding-linux-arm-gnueabihf": "1.2.8", ++ "@rolldown/binding-linux-arm64-gnu": "1.2.8", ++ "@rolldown/binding-linux-arm64-musl": "1.2.8", ++ "@rolldown/binding-linux-ppc64-gnu": "1.2.8", ++ "@rolldown/binding-linux-s390x-gnu": "1.2.8", ++ "@rolldown/binding-linux-x64-gnu": "1.2.8", ++ "@rolldown/binding-linux-x64-musl": "1.2.8", ++ "@rolldown/binding-openharmony-arm64": "1.2.8", ++ "@rolldown/binding-win32-arm64-msvc": "1.2.8", ++ "@rolldown/binding-win32-x64-msvc": "1.2.8" + } + }, + "node_modules/rrweb-cssom": { +@@ -2274,25 +1996,12 @@ + "license": "MIT" + }, + "node_modules/std-env": { +- "version": "3.10.0", +- "resolved": "https://registry.npmjs.org/std-env/-/std-env-3.10.0.tgz", +- "integrity": "sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==", ++ "version": "4.2.0", ++ "resolved": "https://registry.npmjs.org/std-env/-/std-env-4.2.0.tgz", ++ "integrity": "sha512-oCUKSupKTHX53EyjDtuZQ64pjLJ6yYCtpmEw0goYxtjG9KpbRe8KAsl2tBUGU9DyMcJ0RwJ8GqJAFzMXcXW1Rw==", + "dev": true, + "license": "MIT" + }, +- "node_modules/strip-literal": { +- "version": "3.1.0", +- "resolved": "https://registry.npmjs.org/strip-literal/-/strip-literal-3.1.0.tgz", +- "integrity": "sha512-8r3mkIM/2+PpjHoOtiAW8Rg3jJLHaV7xPwG+YRGrv6FP0wwk/toTpATxWYOW0BKdWwl82VT2tFYi5DlROa0Mxg==", +- "dev": true, +- "license": "MIT", +- "dependencies": { +- "js-tokens": "^9.0.1" +- }, +- "funding": { +- "url": "https://github.com/sponsors/antfu" +- } +- }, + "node_modules/symbol-tree": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz", +@@ -2314,21 +2023,24 @@ + "license": "MIT" + }, + "node_modules/tinyexec": { +- "version": "0.3.2", +- "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-0.3.2.tgz", +- "integrity": "sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA==", ++ "version": "1.3.1", ++ "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.3.1.tgz", ++ "integrity": "sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA==", + "dev": true, +- "license": "MIT" ++ "license": "MIT", ++ "engines": { ++ "node": ">=18" ++ } + }, + "node_modules/tinyglobby": { +- "version": "0.2.15", +- "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz", +- "integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==", ++ "version": "0.2.17", ++ "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", ++ "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", +- "picomatch": "^4.0.3" ++ "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" +@@ -2337,30 +2049,10 @@ + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, +- "node_modules/tinypool": { +- "version": "1.1.1", +- "resolved": "https://registry.npmjs.org/tinypool/-/tinypool-1.1.1.tgz", +- "integrity": "sha512-Zba82s87IFq9A9XmjiX5uZA/ARWDrB03OHlq+Vw1fSdt0I+4/Kutwy8BP4Y/y/aORMo61FQ0vIb5j44vSo5Pkg==", +- "dev": true, +- "license": "MIT", +- "engines": { +- "node": "^18.0.0 || >=20.0.0" +- } +- }, + "node_modules/tinyrainbow": { +- "version": "2.0.0", +- "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-2.0.0.tgz", +- "integrity": "sha512-op4nsTR47R6p0vMUUoYl/a+ljLFVtlfaXkLQmqfLR1qHma1h/ysYk4hEXZ880bf2CYgTskvTa/e196Vd5dDQXw==", +- "dev": true, +- "license": "MIT", +- "engines": { +- "node": ">=14.0.0" +- } +- }, +- "node_modules/tinyspy": { +- "version": "4.0.4", +- "resolved": "https://registry.npmjs.org/tinyspy/-/tinyspy-4.0.4.tgz", +- "integrity": "sha512-azl+t0z7pw/z958Gy9svOTuzqIk6xq+NSheJzn5MMWtWTFywIacg2wUlzKFGtt3cthx0r2SxMK0yzJOR0IES7Q==", ++ "version": "3.1.1", ++ "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-3.1.1.tgz", ++ "integrity": "sha512-yau8yJdTt989Mm0Bd/236QnzEiPf2xLLTqUZRUJOo/3CB078LSwzei343DgtJVmfJKJE3TMINY1u42SQsP6mXw==", + "dev": true, + "license": "MIT", + "engines": { +@@ -2414,18 +2106,17 @@ + } + }, + "node_modules/vite": { +- "version": "7.3.1", +- "resolved": "https://registry.npmjs.org/vite/-/vite-7.3.1.tgz", +- "integrity": "sha512-w+N7Hifpc3gRjZ63vYBXA56dvvRlNWRczTdmCBBa+CotUzAPf5b7YMdMR/8CQoeYE5LX3W4wj6RYTgonm1b9DA==", ++ "version": "8.3.0", ++ "resolved": "https://registry.npmjs.org/vite/-/vite-8.3.0.tgz", ++ "integrity": "sha512-lhZBVvEHefgE+HQZC9O7EBJgCU/nVzFNl7vkS4RE0APtWLP02/8QVIkQtzBxPquh7lq5/78NHipTj7ODQ6XuyQ==", + "dev": true, + "license": "MIT", + "dependencies": { +- "esbuild": "^0.27.0", +- "fdir": "^6.5.0", +- "picomatch": "^4.0.3", +- "postcss": "^8.5.6", +- "rollup": "^4.43.0", +- "tinyglobby": "^0.2.15" ++ "lightningcss": "^1.33.0", ++ "picomatch": "^4.0.7", ++ "postcss": "^8.5.28", ++ "rolldown": "~1.2.6", ++ "tinyglobby": "^0.2.17" + }, + "bin": { + "vite": "bin/vite.js" +@@ -2441,9 +2132,10 @@ + }, + "peerDependencies": { + "@types/node": "^20.19.0 || >=22.12.0", ++ "@vitejs/devtools": "^0.7.1", ++ "esbuild": "^0.27.0 || ^0.28.0", + "jiti": ">=1.21.0", + "less": "^4.0.0", +- "lightningcss": "^1.21.0", + "sass": "^1.70.0", + "sass-embedded": "^1.70.0", + "stylus": ">=0.54.8", +@@ -2456,13 +2148,16 @@ + "@types/node": { + "optional": true + }, +- "jiti": { ++ "@vitejs/devtools": { + "optional": true + }, +- "less": { ++ "esbuild": { + "optional": true + }, +- "lightningcss": { ++ "jiti": { ++ "optional": true ++ }, ++ "less": { + "optional": true + }, + "sass": { +@@ -2488,148 +2183,80 @@ + } + } + }, +- "node_modules/vite-node": { +- "version": "3.2.4", +- "resolved": "https://registry.npmjs.org/vite-node/-/vite-node-3.2.4.tgz", +- "integrity": "sha512-EbKSKh+bh1E1IFxeO0pg1n4dvoOTt0UDiXMd/qn++r98+jPO1xtJilvXldeuQ8giIB5IkpjCgMleHMNEsGH6pg==", +- "dev": true, +- "license": "MIT", +- "dependencies": { +- "cac": "^6.7.14", +- "debug": "^4.4.1", +- "es-module-lexer": "^1.7.0", +- "pathe": "^2.0.3", +- "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0" +- }, +- "bin": { +- "vite-node": "vite-node.mjs" +- }, +- "engines": { +- "node": "^18.0.0 || ^20.0.0 || >=22.0.0" +- }, +- "funding": { +- "url": "https://opencollective.com/vitest" +- } +- }, +- "node_modules/vite/node_modules/@esbuild/linux-loong64": { +- "version": "0.27.4", +- "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.27.4.tgz", +- "integrity": "sha512-8mL/vh8qeCoRcFH2nM8wm5uJP+ZcVYGGayMavi8GmRJjuI3g1v6Z7Ni0JJKAJW+m0EtUuARb6Lmp4hMjzCBWzA==", +- "cpu": [ +- "loong64" +- ], +- "dev": true, +- "license": "MIT", +- "optional": true, +- "os": [ +- "linux" +- ], +- "engines": { +- "node": ">=18" +- } +- }, +- "node_modules/vite/node_modules/esbuild": { +- "version": "0.27.4", +- "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.27.4.tgz", +- "integrity": "sha512-Rq4vbHnYkK5fws5NF7MYTU68FPRE1ajX7heQ/8QXXWqNgqqJ/GkmmyxIzUnf2Sr/bakf8l54716CcMGHYhMrrQ==", +- "dev": true, +- "hasInstallScript": true, +- "license": "MIT", +- "bin": { +- "esbuild": "bin/esbuild" +- }, +- "engines": { +- "node": ">=18" +- }, +- "optionalDependencies": { +- "@esbuild/aix-ppc64": "0.27.4", +- "@esbuild/android-arm": "0.27.4", +- "@esbuild/android-arm64": "0.27.4", +- "@esbuild/android-x64": "0.27.4", +- "@esbuild/darwin-arm64": "0.27.4", +- "@esbuild/darwin-x64": "0.27.4", +- "@esbuild/freebsd-arm64": "0.27.4", +- "@esbuild/freebsd-x64": "0.27.4", +- "@esbuild/linux-arm": "0.27.4", +- "@esbuild/linux-arm64": "0.27.4", +- "@esbuild/linux-ia32": "0.27.4", +- "@esbuild/linux-loong64": "0.27.4", +- "@esbuild/linux-mips64el": "0.27.4", +- "@esbuild/linux-ppc64": "0.27.4", +- "@esbuild/linux-riscv64": "0.27.4", +- "@esbuild/linux-s390x": "0.27.4", +- "@esbuild/linux-x64": "0.27.4", +- "@esbuild/netbsd-arm64": "0.27.4", +- "@esbuild/netbsd-x64": "0.27.4", +- "@esbuild/openbsd-arm64": "0.27.4", +- "@esbuild/openbsd-x64": "0.27.4", +- "@esbuild/openharmony-arm64": "0.27.4", +- "@esbuild/sunos-x64": "0.27.4", +- "@esbuild/win32-arm64": "0.27.4", +- "@esbuild/win32-ia32": "0.27.4", +- "@esbuild/win32-x64": "0.27.4" +- } +- }, + "node_modules/vitest": { +- "version": "3.2.4", +- "resolved": "https://registry.npmjs.org/vitest/-/vitest-3.2.4.tgz", +- "integrity": "sha512-LUCP5ev3GURDysTWiP47wRRUpLKMOfPh+yKTx3kVIEiu5KOMeqzpnYNsKyOoVrULivR8tLcks4+lga33Whn90A==", ++ "version": "4.1.11", ++ "resolved": "https://registry.npmjs.org/vitest/-/vitest-4.1.11.tgz", ++ "integrity": "sha512-fhACrNXUidIbGSBr5FlbuBkO7VWC1ZyLl0DO4CU2DrQoAPxX84Ysxs+HeGQpii5lZWV1Q4gBZTTu49mF+A6Edw==", + "dev": true, + "license": "MIT", + "dependencies": { +- "@types/chai": "^5.2.2", +- "@vitest/expect": "3.2.4", +- "@vitest/mocker": "3.2.4", +- "@vitest/pretty-format": "^3.2.4", +- "@vitest/runner": "3.2.4", +- "@vitest/snapshot": "3.2.4", +- "@vitest/spy": "3.2.4", +- "@vitest/utils": "3.2.4", +- "chai": "^5.2.0", +- "debug": "^4.4.1", +- "expect-type": "^1.2.1", +- "magic-string": "^0.30.17", ++ "@vitest/expect": "4.1.11", ++ "@vitest/mocker": "4.1.11", ++ "@vitest/pretty-format": "4.1.11", ++ "@vitest/runner": "4.1.11", ++ "@vitest/snapshot": "4.1.11", ++ "@vitest/spy": "4.1.11", ++ "@vitest/utils": "4.1.11", ++ "es-module-lexer": "^2.0.0", ++ "expect-type": "^1.3.0", ++ "magic-string": "^0.30.21", ++ "obug": "^2.1.1", + "pathe": "^2.0.3", +- "picomatch": "^4.0.2", +- "std-env": "^3.9.0", ++ "picomatch": "^4.0.3", ++ "std-env": "^4.0.0-rc.1", + "tinybench": "^2.9.0", +- "tinyexec": "^0.3.2", +- "tinyglobby": "^0.2.14", +- "tinypool": "^1.1.1", +- "tinyrainbow": "^2.0.0", +- "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0", +- "vite-node": "3.2.4", ++ "tinyexec": "^1.0.2", ++ "tinyglobby": "^0.2.15", ++ "tinyrainbow": "^3.1.0", ++ "vite": "^6.0.0 || ^7.0.0 || ^8.0.0", + "why-is-node-running": "^2.3.0" + }, + "bin": { + "vitest": "vitest.mjs" + }, + "engines": { +- "node": "^18.0.0 || ^20.0.0 || >=22.0.0" ++ "node": "^20.0.0 || ^22.0.0 || >=24.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@edge-runtime/vm": "*", +- "@types/debug": "^4.1.12", +- "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", +- "@vitest/browser": "3.2.4", +- "@vitest/ui": "3.2.4", ++ "@opentelemetry/api": "^1.9.0", ++ "@types/node": "^20.0.0 || ^22.0.0 || >=24.0.0", ++ "@vitest/browser-playwright": "4.1.11", ++ "@vitest/browser-preview": "4.1.11", ++ "@vitest/browser-webdriverio": "4.1.11", ++ "@vitest/coverage-istanbul": "4.1.11", ++ "@vitest/coverage-v8": "4.1.11", ++ "@vitest/ui": "4.1.11", + "happy-dom": "*", +- "jsdom": "*" ++ "jsdom": "*", ++ "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "@edge-runtime/vm": { + "optional": true + }, +- "@types/debug": { ++ "@opentelemetry/api": { + "optional": true + }, + "@types/node": { + "optional": true + }, +- "@vitest/browser": { ++ "@vitest/browser-playwright": { ++ "optional": true ++ }, ++ "@vitest/browser-preview": { ++ "optional": true ++ }, ++ "@vitest/browser-webdriverio": { ++ "optional": true ++ }, ++ "@vitest/coverage-istanbul": { ++ "optional": true ++ }, ++ "@vitest/coverage-v8": { + "optional": true + }, + "@vitest/ui": { +@@ -2640,6 +2267,9 @@ + }, + "jsdom": { + "optional": true ++ }, ++ "vite": { ++ "optional": false + } + } + }, +diff --git a/package.json b/package.json +index 89ae6989..fd0c48b7 100644 +--- a/package.json ++++ b/package.json +@@ -14,7 +14,7 @@ + "brotli-size": "^4.0.0", + "esbuild": "^0.14.49", + "jsdom": "27.0.0", +- "vitest": "^3.2.4" ++ "vitest": "^4.1.11" + }, + "dependencies": { + "@alpinejs/anchor": "^3.17.2", diff --git a/tasks/livewire__livewire-10697/solution/solve.sh b/tasks/livewire__livewire-10697/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/livewire__livewire-10697/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/livewire__livewire-10697/task.toml b/tasks/livewire__livewire-10697/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..6c9f1e06a1fe6435eb3d740bfc444270eea5d4fb --- /dev/null +++ b/tasks/livewire__livewire-10697/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/livewire__livewire-10697" +description = "Upgrade Vitest to patched 4.1 line" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "livewire", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "livewire/livewire" +ref = "31b12dd0f4b44bfa9a5c2fb3d13dd93ad35dad3f" +reference = "https://github.com/livewire/livewire/pull/10697" +source_access = "auto" +built_at = "2026-11-16T16:09:51.494696+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:a327d70bd647416b3c0f7162fc18dea4370cbef1a6203891f3eae47af564532f" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-10T12:15:41Z" +diff_format = "unified" +context_files = [ + "package-lock.json", + "package.json", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 1524 +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.412940+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:9c1576e5274971d0c241399ceaa8921a4456a2f89cfe39c5a5ac1ec7a1ba1762" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/livewire__livewire-10697/tests/capture.py b/tasks/livewire__livewire-10697/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/livewire__livewire-10697/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/livewire__livewire-10697/tests/instruction.md b/tasks/livewire__livewire-10697/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c15a969a96ea6f7784983482a983d3219c677108 --- /dev/null +++ b/tasks/livewire__livewire-10697/tests/instruction.md @@ -0,0 +1,17 @@ +# Issue + +**Title:** Upgrade Vitest to patched 4.1 line + +## Description + +Updates Vitest from 3.2.4 to the patched 4.1.11 line without taking the breaking 5.0 upgrade proposed by Dependabot in #10691. The 5.0 jump pulls Vite 8 and fails dependency installation against the repository esbuild pin. + +Verified locally: +- npm ci --ignore-scripts +- npm run build +- npm run test:run (110 passed, 1 skipped) +- git diff --check + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `31b12dd0f4b4`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10697/tests/oracle.patch b/tasks/livewire__livewire-10697/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..dbeff520694d5249c4fb4266eb1749aa5d286135 --- /dev/null +++ b/tasks/livewire__livewire-10697/tests/oracle.patch @@ -0,0 +1,1995 @@ +diff --git a/package-lock.json b/package-lock.json +index 2f324395..0788dec8 100644 +--- a/package-lock.json ++++ b/package-lock.json +@@ -25,7 +25,7 @@ + "brotli-size": "^4.0.0", + "esbuild": "^0.14.49", + "jsdom": "27.0.0", +- "vitest": "^3.2.4" ++ "vitest": "^4.1.11" + } + }, + "node_modules/@alpinejs/anchor": { +@@ -276,63 +276,71 @@ + "node": ">=20.19.0" + } + }, +- "node_modules/@esbuild/aix-ppc64": { +- "version": "0.27.4", +- "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.4.tgz", +- "integrity": "sha512-cQPwL2mp2nSmHHJlCyoXgHGhbEPMrEEU5xhkcy3Hs/O7nGZqEpZ2sUtLaL9MORLtDfRvVl2/3PAuEkYZH0Ty8Q==", ++ "node_modules/@esbuild/linux-loong64": { ++ "version": "0.14.54", ++ "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.14.54.tgz", ++ "integrity": "sha512-bZBrLAIX1kpWelV0XemxBZllyRmM6vgFQQG2GdNb+r3Fkp0FOh1NJSvekXDs7jq70k4euu1cryLMfU+mTXlEpw==", + "cpu": [ +- "ppc64" ++ "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ +- "aix" ++ "linux" + ], + "engines": { +- "node": ">=18" ++ "node": ">=12" + } + }, +- "node_modules/@esbuild/android-arm": { +- "version": "0.27.4", +- "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.27.4.tgz", +- "integrity": "sha512-X9bUgvxiC8CHAGKYufLIHGXPJWnr0OCdR0anD2e21vdvgCI8lIfqFbnoeOz7lBjdrAGUhqLZLcQo6MLhTO2DKQ==", +- "cpu": [ +- "arm" +- ], +- "dev": true, ++ "node_modules/@floating-ui/core": { ++ "version": "1.7.5", ++ "resolved": "https://registry.npmjs.org/@floating-ui/core/-/core-1.7.5.tgz", ++ "integrity": "sha512-1Ih4WTWyw0+lKyFMcBHGbb5U5FtuHJuujoyyr5zTaWS5EYMeT6Jb2AuDeftsCsEuchO+mM2ij5+q9crhydzLhQ==", + "license": "MIT", +- "optional": true, +- "os": [ +- "android" +- ], +- "engines": { +- "node": ">=18" ++ "dependencies": { ++ "@floating-ui/utils": "^0.2.11" + } + }, +- "node_modules/@esbuild/android-arm64": { +- "version": "0.27.4", +- "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.27.4.tgz", +- "integrity": "sha512-gdLscB7v75wRfu7QSm/zg6Rx29VLdy9eTr2t44sfTW7CxwAtQghZ4ZnqHk3/ogz7xao0QAgrkradbBzcqFPasw==", +- "cpu": [ +- "arm64" +- ], ++ "node_modules/@floating-ui/dom": { ++ "version": "1.7.6", ++ "resolved": "https://registry.npmjs.org/@floating-ui/dom/-/dom-1.7.6.tgz", ++ "integrity": "sha512-9gZSAI5XM36880PPMm//9dfiEngYoC6Am2izES1FF406YFsjvyBMmeJ2g4SAju3xWwtuynNRFL2s9hgxpLI5SQ==", ++ "license": "MIT", ++ "dependencies": { ++ "@floating-ui/core": "^1.7.5", ++ "@floating-ui/utils": "^0.2.11" ++ } ++ }, ++ "node_modules/@floating-ui/utils": { ++ "version": "0.2.11", ++ "resolved": "https://registry.npmjs.org/@floating-ui/utils/-/utils-0.2.11.tgz", ++ "integrity": "sha512-RiB/yIh78pcIxl6lLMG0CgBXAZ2Y0eVHqMPYugu+9U0AeT6YBeiJpf7lbdJNIugFP5SIjwNRgo4DhR1Qxi26Gg==", ++ "license": "MIT" ++ }, ++ "node_modules/@jridgewell/sourcemap-codec": { ++ "version": "1.6.0", ++ "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", ++ "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", ++ "dev": true, ++ "license": "MIT" ++ }, ++ "node_modules/@oxc-project/types": { ++ "version": "0.149.0", ++ "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.149.0.tgz", ++ "integrity": "sha512-Efcc+iF0j3Bf67YjEqIqWXbX5XddXoK/Mw4K1/JuXwRCZ8N16VR7iT23nlCc9XrveFVh/E5Rqs2StT0V8v9LdA==", + "dev": true, + "license": "MIT", +- "optional": true, +- "os": [ +- "android" +- ], +- "engines": { +- "node": ">=18" ++ "funding": { ++ "url": "https://github.com/sponsors/oxc-project" + } + }, +- "node_modules/@esbuild/android-x64": { +- "version": "0.27.4", +- "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.27.4.tgz", +- "integrity": "sha512-PzPFnBNVF292sfpfhiyiXCGSn9HZg5BcAz+ivBuSsl6Rk4ga1oEXAamhOXRFyMcjwr2DVtm40G65N3GLeH1Lvw==", ++ "node_modules/@rolldown/binding-android-arm-eabi": { ++ "version": "1.2.8", ++ "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.8.tgz", ++ "integrity": "sha512-tN5aztYkKCte4i5SIrrz5yK/HMjEuCqCSCJa418jOV8tZ1cBY3YF2otxB1ktPxzsLA1BeTqwapK0bfjxNvHJVw==", + "cpu": [ +- "x64" ++ "arm" + ], + "dev": true, + "license": "MIT", +@@ -341,13 +349,13 @@ + "android" + ], + "engines": { +- "node": ">=18" ++ "node": "^20.19.0 || >=22.12.0" + } + }, +- "node_modules/@esbuild/darwin-arm64": { +- "version": "0.27.4", +- "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.27.4.tgz", +- "integrity": "sha512-b7xaGIwdJlht8ZFCvMkpDN6uiSmnxxK56N2GDTMYPr2/gzvfdQN8rTfBsvVKmIVY/X7EM+/hJKEIbbHs9oA4tQ==", ++ "node_modules/@rolldown/binding-android-arm64": { ++ "version": "1.2.8", ++ "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.8.tgz", ++ "integrity": "sha512-dIYTWl9XprMUiQFoc55KUyk/oS8SKYH3zFl0LTR7RT0Xj4hgSVyuJcroH8JUu8RcpF8fTB6E0aOwCkZoYPcDSQ==", + "cpu": [ + "arm64" + ], +@@ -355,18 +363,18 @@ + "license": "MIT", + "optional": true, + "os": [ +- "darwin" ++ "android" + ], + "engines": { +- "node": ">=18" ++ "node": "^20.19.0 || >=22.12.0" + } + }, +- "node_modules/@esbuild/darwin-x64": { +- "version": "0.27.4", +- "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.27.4.tgz", +- "integrity": "sha512-sR+OiKLwd15nmCdqpXMnuJ9W2kpy0KigzqScqHI3Hqwr7IXxBp3Yva+yJwoqh7rE8V77tdoheRYataNKL4QrPw==", ++ "node_modules/@rolldown/binding-darwin-arm64": { ++ "version": "1.2.8", ++ "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.8.tgz", ++ "integrity": "sha512-PCSDQGXD2IyTEFrcgPyBM8jJuGmrbCMuoIOXdbEGVemruKACXoLQJrb+A45Z0L5t1RQkdfJprAYPkikbh7dzdA==", + "cpu": [ +- "x64" ++ "arm64" + ], + "dev": true, + "license": "MIT", +@@ -375,30 +383,30 @@ + "darwin" + ], + "engines": { +- "node": ">=18" ++ "node": "^20.19.0 || >=22.12.0" + } + }, +- "node_modules/@esbuild/freebsd-arm64": { +- "version": "0.27.4", +- "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.27.4.tgz", +- "integrity": "sha512-jnfpKe+p79tCnm4GVav68A7tUFeKQwQyLgESwEAUzyxk/TJr4QdGog9sqWNcUbr/bZt/O/HXouspuQDd9JxFSw==", ++ "node_modules/@rolldown/binding-darwin-x64": { ++ "version": "1.2.8", ++ "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.8.tgz", ++ "integrity": "sha512-Uk7lRsGhPFHVX/sAUC6D5H9Ol30dFHd6iquokll2th3LpdJ3F5CzQB+7DHn0Ri2mG+U7k2zXiPHDrwZenXhwSA==", + "cpu": [ +- "arm64" ++ "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ +- "freebsd" ++ "darwin" + ], + "engines": { +- "node": ">=18" ++ "node": "^20.19.0 || >=22.12.0" + } + }, +- "node_modules/@esbuild/freebsd-x64": { +- "version": "0.27.4", +- "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.27.4.tgz", +- "integrity": "sha512-2kb4ceA/CpfUrIcTUl1wrP/9ad9Atrp5J94Lq69w7UwOMolPIGrfLSvAKJp0RTvkPPyn6CIWrNy13kyLikZRZQ==", ++ "node_modules/@rolldown/binding-freebsd-x64": { ++ "version": "1.2.8", ++ "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.8.tgz", ++ "integrity": "sha512-DjszaTEVogPqA5bYzsEeqDCQxbcp2fexQwKcRspYji2yzR68fCf+e4fx6kBSRDwX5/brZaHw/hWS9+A/+/w9sQ==", + "cpu": [ + "x64" + ], +@@ -409,13 +417,13 @@ + "freebsd" + ], + "engines": { +- "node": ">=18" ++ "node": "^20.19.0 || >=22.12.0" + } + }, +- "node_modules/@esbuild/linux-arm": { +- "version": "0.27.4", +- "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.27.4.tgz", +- "integrity": "sha512-aBYgcIxX/wd5n2ys0yESGeYMGF+pv6g0DhZr3G1ZG4jMfruU9Tl1i2Z+Wnj9/KjGz1lTLCcorqE2viePZqj4Eg==", ++ "node_modules/@rolldown/binding-linux-arm-gnueabihf": { ++ "version": "1.2.8", ++ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.8.tgz", ++ "integrity": "sha512-zmwa7FTmdzB6aaEEuuls18H6Ap5JmJPSoPTuXixeJZV6tG40SyLkApQtz1g8ptZtiEKqj9OM0oNLPh1AgvE31Q==", + "cpu": [ + "arm" + ], +@@ -426,13 +434,13 @@ + "linux" + ], + "engines": { +- "node": ">=18" ++ "node": "^20.19.0 || >=22.12.0" + } + }, +- "node_modules/@esbuild/linux-arm64": { +- "version": "0.27.4", +- "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.27.4.tgz", +- "integrity": "sha512-7nQOttdzVGth1iz57kxg9uCz57dxQLHWxopL6mYuYthohPKEK0vU0C3O21CcBK6KDlkYVcnDXY099HcCDXd9dA==", ++ "node_modules/@rolldown/binding-linux-arm64-gnu": { ++ "version": "1.2.8", ++ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.8.tgz", ++ "integrity": "sha512-KdYQDPHwJVnbFwdTGMgxsI9SqblBlz6STGM+w1We/d5B8OWWidYH0MwkU/uA1wM5fIpO2MkOVxXrNzzuZhw9ew==", + "cpu": [ + "arm64" + ], +@@ -443,49 +451,15 @@ + "linux" + ], + "engines": { +- "node": ">=18" +- } +- }, +- "node_modules/@esbuild/linux-ia32": { +- "version": "0.27.4", +- "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.27.4.tgz", +- "integrity": "sha512-oPtixtAIzgvzYcKBQM/qZ3R+9TEUd1aNJQu0HhGyqtx6oS7qTpvjheIWBbes4+qu1bNlo2V4cbkISr8q6gRBFA==", +- "cpu": [ +- "ia32" +- ], +- "dev": true, +- "license": "MIT", +- "optional": true, +- "os": [ +- "linux" +- ], +- "engines": { +- "node": ">=18" +- } +- }, +- "node_modules/@esbuild/linux-loong64": { +- "version": "0.14.54", +- "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.14.54.tgz", +- "integrity": "sha512-bZBrLAIX1kpWelV0XemxBZllyRmM6vgFQQG2GdNb+r3Fkp0FOh1NJSvekXDs7jq70k4euu1cryLMfU+mTXlEpw==", +- "cpu": [ +- "loong64" +- ], +- "dev": true, +- "license": "MIT", +- "optional": true, +- "os": [ +- "linux" +- ], +- "engines": { +- "node": ">=12" ++ "node": "^20.19.0 || >=22.12.0" + } + }, +- "node_modules/@esbuild/linux-mips64el": { +- "version": "0.27.4", +- "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.27.4.tgz", +- "integrity": "sha512-1RdrWFFiiLIW7LQq9Q2NES+HiD4NyT8Itj9AUeCl0IVCA459WnPhREKgwrpaIfTOe+/2rdntisegiPWn/r/aAw==", ++ "node_modules/@rolldown/binding-linux-arm64-musl": { ++ "version": "1.2.8", ++ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.8.tgz", ++ "integrity": "sha512-jFJTifHnNPY+yzOoNZQfSIysrVyXzEQPhPnOUjmD1bcQGHH6s7c8cViKWar8YplQImE5N9JRqMCLrM2CdxOrZA==", + "cpu": [ +- "mips64el" ++ "arm64" + ], + "dev": true, + "license": "MIT", +@@ -494,13 +468,13 @@ + "linux" + ], + "engines": { +- "node": ">=18" ++ "node": "^20.19.0 || >=22.12.0" + } + }, +- "node_modules/@esbuild/linux-ppc64": { +- "version": "0.27.4", +- "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.27.4.tgz", +- "integrity": "sha512-tLCwNG47l3sd9lpfyx9LAGEGItCUeRCWeAx6x2Jmbav65nAwoPXfewtAdtbtit/pJFLUWOhpv0FpS6GQAmPrHA==", ++ "node_modules/@rolldown/binding-linux-ppc64-gnu": { ++ "version": "1.2.8", ++ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.8.tgz", ++ "integrity": "sha512-FhiOziBDWPBjbcmRzfLyIJnaP7AVMFXT7YCXPjXxj7wKU3vx24RjrCNN/zjvVa+N2vVoHJwCoUBvsrN/DG3zIA==", + "cpu": [ + "ppc64" + ], +@@ -511,30 +485,13 @@ + "linux" + ], + "engines": { +- "node": ">=18" +- } +- }, +- "node_modules/@esbuild/linux-riscv64": { +- "version": "0.27.4", +- "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.27.4.tgz", +- "integrity": "sha512-BnASypppbUWyqjd1KIpU4AUBiIhVr6YlHx/cnPgqEkNoVOhHg+YiSVxM1RLfiy4t9cAulbRGTNCKOcqHrEQLIw==", +- "cpu": [ +- "riscv64" +- ], +- "dev": true, +- "license": "MIT", +- "optional": true, +- "os": [ +- "linux" +- ], +- "engines": { +- "node": ">=18" ++ "node": "^20.19.0 || >=22.12.0" + } + }, +- "node_modules/@esbuild/linux-s390x": { +- "version": "0.27.4", +- "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.27.4.tgz", +- "integrity": "sha512-+eUqgb/Z7vxVLezG8bVB9SfBie89gMueS+I0xYh2tJdw3vqA/0ImZJ2ROeWwVJN59ihBeZ7Tu92dF/5dy5FttA==", ++ "node_modules/@rolldown/binding-linux-s390x-gnu": { ++ "version": "1.2.8", ++ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.8.tgz", ++ "integrity": "sha512-WnHfADMzOV2Y55wlx1hzzQnar/wDt/VdvWSD99r18Mz9ylNieIGOkRx3UV21h7m/eJvjySYJkO26VvGNFkwsIQ==", + "cpu": [ + "s390x" + ], +@@ -545,13 +502,13 @@ + "linux" + ], + "engines": { +- "node": ">=18" ++ "node": "^20.19.0 || >=22.12.0" + } + }, +- "node_modules/@esbuild/linux-x64": { +- "version": "0.27.4", +- "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.27.4.tgz", +- "integrity": "sha512-S5qOXrKV8BQEzJPVxAwnryi2+Iq5pB40gTEIT69BQONqR7JH1EPIcQ/Uiv9mCnn05jff9umq/5nqzxlqTOg9NA==", ++ "node_modules/@rolldown/binding-linux-x64-gnu": { ++ "version": "1.2.8", ++ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.8.tgz", ++ "integrity": "sha512-H9tRr5ibfXFVLxbPOseVewewFpl28zcEdjRDt2FTUZU7odxP0gEv1ki4/kGmcGOh78oRwZuuQllGLZ9zTJp84g==", + "cpu": [ + "x64" + ], +@@ -562,64 +519,13 @@ + "linux" + ], + "engines": { +- "node": ">=18" +- } +- }, +- "node_modules/@esbuild/netbsd-arm64": { +- "version": "0.27.4", +- "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.27.4.tgz", +- "integrity": "sha512-xHT8X4sb0GS8qTqiwzHqpY00C95DPAq7nAwX35Ie/s+LO9830hrMd3oX0ZMKLvy7vsonee73x0lmcdOVXFzd6Q==", +- "cpu": [ +- "arm64" +- ], +- "dev": true, +- "license": "MIT", +- "optional": true, +- "os": [ +- "netbsd" +- ], +- "engines": { +- "node": ">=18" +- } +- }, +- "node_modules/@esbuild/netbsd-x64": { +- "version": "0.27.4", +- "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.27.4.tgz", +- "integrity": "sha512-RugOvOdXfdyi5Tyv40kgQnI0byv66BFgAqjdgtAKqHoZTbTF2QqfQrFwa7cHEORJf6X2ht+l9ABLMP0dnKYsgg==", +- "cpu": [ +- "x64" +- ], +- "dev": true, +- "license": "MIT", +- "optional": true, +- "os": [ +- "netbsd" +- ], +- "engines": { +- "node": ">=18" +- } +- }, +- "node_modules/@esbuild/openbsd-arm64": { +- "version": "0.27.4", +- "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.27.4.tgz", +- "integrity": "sha512-2MyL3IAaTX+1/qP0O1SwskwcwCoOI4kV2IBX1xYnDDqthmq5ArrW94qSIKCAuRraMgPOmG0RDTA74mzYNQA9ow==", +- "cpu": [ +- "arm64" +- ], +- "dev": true, +- "license": "MIT", +- "optional": true, +- "os": [ +- "openbsd" +- ], +- "engines": { +- "node": ">=18" ++ "node": "^20.19.0 || >=22.12.0" + } + }, +- "node_modules/@esbuild/openbsd-x64": { +- "version": "0.27.4", +- "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.27.4.tgz", +- "integrity": "sha512-u8fg/jQ5aQDfsnIV6+KwLOf1CmJnfu1ShpwqdwC0uA7ZPwFws55Ngc12vBdeUdnuWoQYx/SOQLGDcdlfXhYmXQ==", ++ "node_modules/@rolldown/binding-linux-x64-musl": { ++ "version": "1.2.8", ++ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.8.tgz", ++ "integrity": "sha512-UefiqfM3D6IVNlZ8tSGs9+Ejjud2T+oxO0IHADU45Y+lyEjD2dVFyZHbkfX0LUb5Zugo/oIv1eCO/KVYhgYJYA==", + "cpu": [ + "x64" + ], +@@ -627,16 +533,16 @@ + "license": "MIT", + "optional": true, + "os": [ +- "openbsd" ++ "linux" + ], + "engines": { +- "node": ">=18" ++ "node": "^20.19.0 || >=22.12.0" + } + }, +- "node_modules/@esbuild/openharmony-arm64": { +- "version": "0.27.4", +- "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.27.4.tgz", +- "integrity": "sha512-JkTZrl6VbyO8lDQO3yv26nNr2RM2yZzNrNHEsj9bm6dOwwu9OYN28CjzZkH57bh4w0I2F7IodpQvUAEd1mbWXg==", ++ "node_modules/@rolldown/binding-openharmony-arm64": { ++ "version": "1.2.8", ++ "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.8.tgz", ++ "integrity": "sha512-637Ke4kWSy6rp9cxQ9gMOXlxPgIw/c1beASV4M//3+9I4uwBVOOl74G+e3zyU3u19U7RkRl/HuewixZ/Z6+Rjg==", + "cpu": [ + "arm64" + ], +@@ -647,30 +553,13 @@ + "openharmony" + ], + "engines": { +- "node": ">=18" +- } +- }, +- "node_modules/@esbuild/sunos-x64": { +- "version": "0.27.4", +- "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.27.4.tgz", +- "integrity": "sha512-/gOzgaewZJfeJTlsWhvUEmUG4tWEY2Spp5M20INYRg2ZKl9QPO3QEEgPeRtLjEWSW8FilRNacPOg8R1uaYkA6g==", +- "cpu": [ +- "x64" +- ], +- "dev": true, +- "license": "MIT", +- "optional": true, +- "os": [ +- "sunos" +- ], +- "engines": { +- "node": ">=18" ++ "node": "^20.19.0 || >=22.12.0" + } + }, +- "node_modules/@esbuild/win32-arm64": { +- "version": "0.27.4", +- "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.27.4.tgz", +- "integrity": "sha512-Z9SExBg2y32smoDQdf1HRwHRt6vAHLXcxD2uGgO/v2jK7Y718Ix4ndsbNMU/+1Qiem9OiOdaqitioZwxivhXYg==", ++ "node_modules/@rolldown/binding-win32-arm64-msvc": { ++ "version": "1.2.8", ++ "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.8.tgz", ++ "integrity": "sha512-xWBkPOF1Q9k/Gv1nQXnVdLxKu74jXppuOM4Z3mnypVUJJJwLsMl7hNJGRAUJoG8A5MgOI1ACKM+wBFxSJzKy4A==", + "cpu": [ + "arm64" + ], +@@ -681,30 +570,13 @@ + "win32" + ], + "engines": { +- "node": ">=18" +- } +- }, +- "node_modules/@esbuild/win32-ia32": { +- "version": "0.27.4", +- "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.27.4.tgz", +- "integrity": "sha512-DAyGLS0Jz5G5iixEbMHi5KdiApqHBWMGzTtMiJ72ZOLhbu/bzxgAe8Ue8CTS3n3HbIUHQz/L51yMdGMeoxXNJw==", +- "cpu": [ +- "ia32" +- ], +- "dev": true, +- "license": "MIT", +- "optional": true, +- "os": [ +- "win32" +- ], +- "engines": { +- "node": ">=18" ++ "node": "^20.19.0 || >=22.12.0" + } + }, +- "node_modules/@esbuild/win32-x64": { +- "version": "0.27.4", +- "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.27.4.tgz", +- "integrity": "sha512-+knoa0BDoeXgkNvvV1vvbZX4+hizelrkwmGJBdT17t8FNPwG2lKemmuMZlmaNQ3ws3DKKCxpb4zRZEIp3UxFCg==", ++ "node_modules/@rolldown/binding-win32-x64-msvc": { ++ "version": "1.2.8", ++ "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.8.tgz", ++ "integrity": "sha512-uz2ZvfgXbxqNwijjjbxrnvALwpyODDcgc1T1N8N3rf/DXKQmaFwmB4LX4yyjggpwN2obdQLb2rgirX5ffCWYng==", + "cpu": [ + "x64" + ], +@@ -715,390 +587,22 @@ + "win32" + ], + "engines": { +- "node": ">=18" +- } +- }, +- "node_modules/@floating-ui/core": { +- "version": "1.7.5", +- "resolved": "https://registry.npmjs.org/@floating-ui/core/-/core-1.7.5.tgz", +- "integrity": "sha512-1Ih4WTWyw0+lKyFMcBHGbb5U5FtuHJuujoyyr5zTaWS5EYMeT6Jb2AuDeftsCsEuchO+mM2ij5+q9crhydzLhQ==", +- "license": "MIT", +- "dependencies": { +- "@floating-ui/utils": "^0.2.11" +- } +- }, +- "node_modules/@floating-ui/dom": { +- "version": "1.7.6", +- "resolved": "https://registry.npmjs.org/@floating-ui/dom/-/dom-1.7.6.tgz", +- "integrity": "sha512-9gZSAI5XM36880PPMm//9dfiEngYoC6Am2izES1FF406YFsjvyBMmeJ2g4SAju3xWwtuynNRFL2s9hgxpLI5SQ==", +- "license": "MIT", +- "dependencies": { +- "@floating-ui/core": "^1.7.5", +- "@floating-ui/utils": "^0.2.11" ++ "node": "^20.19.0 || >=22.12.0" + } + }, +- "node_modules/@floating-ui/utils": { +- "version": "0.2.11", +- "resolved": "https://registry.npmjs.org/@floating-ui/utils/-/utils-0.2.11.tgz", +- "integrity": "sha512-RiB/yIh78pcIxl6lLMG0CgBXAZ2Y0eVHqMPYugu+9U0AeT6YBeiJpf7lbdJNIugFP5SIjwNRgo4DhR1Qxi26Gg==", +- "license": "MIT" +- }, +- "node_modules/@jridgewell/sourcemap-codec": { +- "version": "1.5.5", +- "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", +- "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==", ++ "node_modules/@rolldown/pluginutils": { ++ "version": "1.0.1", ++ "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.1.tgz", ++ "integrity": "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==", + "dev": true, + "license": "MIT" + }, +- "node_modules/@rollup/rollup-android-arm-eabi": { +- "version": "4.60.1", +- "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.60.1.tgz", +- "integrity": "sha512-d6FinEBLdIiK+1uACUttJKfgZREXrF0Qc2SmLII7W2AD8FfiZ9Wjd+rD/iRuf5s5dWrr1GgwXCvPqOuDquOowA==", +- "cpu": [ +- "arm" +- ], +- "dev": true, +- "license": "MIT", +- "optional": true, +- "os": [ +- "android" +- ] +- }, +- "node_modules/@rollup/rollup-android-arm64": { +- "version": "4.60.1", +- "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.60.1.tgz", +- "integrity": "sha512-YjG/EwIDvvYI1YvYbHvDz/BYHtkY4ygUIXHnTdLhG+hKIQFBiosfWiACWortsKPKU/+dUwQQCKQM3qrDe8c9BA==", +- "cpu": [ +- "arm64" +- ], +- "dev": true, +- "license": "MIT", +- "optional": true, +- "os": [ +- "android" +- ] +- }, +- "node_modules/@rollup/rollup-darwin-arm64": { +- "version": "4.60.1", +- "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.60.1.tgz", +- "integrity": "sha512-mjCpF7GmkRtSJwon+Rq1N8+pI+8l7w5g9Z3vWj4T7abguC4Czwi3Yu/pFaLvA3TTeMVjnu3ctigusqWUfjZzvw==", +- "cpu": [ +- "arm64" +- ], +- "dev": true, +- "license": "MIT", +- "optional": true, +- "os": [ +- "darwin" +- ] +- }, +- "node_modules/@rollup/rollup-darwin-x64": { +- "version": "4.60.1", +- "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.60.1.tgz", +- "integrity": "sha512-haZ7hJ1JT4e9hqkoT9R/19XW2QKqjfJVv+i5AGg57S+nLk9lQnJ1F/eZloRO3o9Scy9CM3wQ9l+dkXtcBgN5Ew==", +- "cpu": [ +- "x64" +- ], +- "dev": true, +- "license": "MIT", +- "optional": true, +- "os": [ +- "darwin" +- ] +- }, +- "node_modules/@rollup/rollup-freebsd-arm64": { +- "version": "4.60.1", +- "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.60.1.tgz", +- "integrity": "sha512-czw90wpQq3ZsAVBlinZjAYTKduOjTywlG7fEeWKUA7oCmpA8xdTkxZZlwNJKWqILlq0wehoZcJYfBvOyhPTQ6w==", +- "cpu": [ +- "arm64" +- ], +- "dev": true, +- "license": "MIT", +- "optional": true, +- "os": [ +- "freebsd" +- ] +- }, +- "node_modules/@rollup/rollup-freebsd-x64": { +- "version": "4.60.1", +- "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.60.1.tgz", +- "integrity": "sha512-KVB2rqsxTHuBtfOeySEyzEOB7ltlB/ux38iu2rBQzkjbwRVlkhAGIEDiiYnO2kFOkJp+Z7pUXKyrRRFuFUKt+g==", +- "cpu": [ +- "x64" +- ], +- "dev": true, +- "license": "MIT", +- "optional": true, +- "os": [ +- "freebsd" +- ] +- }, +- "node_modules/@rollup/rollup-linux-arm-gnueabihf": { +- "version": "4.60.1", +- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.60.1.tgz", +- "integrity": "sha512-L+34Qqil+v5uC0zEubW7uByo78WOCIrBvci69E7sFASRl0X7b/MB6Cqd1lky/CtcSVTydWa2WZwFuWexjS5o6g==", +- "cpu": [ +- "arm" +- ], +- "dev": true, +- "license": "MIT", +- "optional": true, +- "os": [ +- "linux" +- ] +- }, +- "node_modules/@rollup/rollup-linux-arm-musleabihf": { +- "version": "4.60.1", +- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.60.1.tgz", +- "integrity": "sha512-n83O8rt4v34hgFzlkb1ycniJh7IR5RCIqt6mz1VRJD6pmhRi0CXdmfnLu9dIUS6buzh60IvACM842Ffb3xd6Gg==", +- "cpu": [ +- "arm" +- ], +- "dev": true, +- "license": "MIT", +- "optional": true, +- "os": [ +- "linux" +- ] +- }, +- "node_modules/@rollup/rollup-linux-arm64-gnu": { +- "version": "4.60.1", +- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.60.1.tgz", +- "integrity": "sha512-Nql7sTeAzhTAja3QXeAI48+/+GjBJ+QmAH13snn0AJSNL50JsDqotyudHyMbO2RbJkskbMbFJfIJKWA6R1LCJQ==", +- "cpu": [ +- "arm64" +- ], +- "dev": true, +- "license": "MIT", +- "optional": true, +- "os": [ +- "linux" +- ] +- }, +- "node_modules/@rollup/rollup-linux-arm64-musl": { +- "version": "4.60.1", +- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.60.1.tgz", +- "integrity": "sha512-+pUymDhd0ys9GcKZPPWlFiZ67sTWV5UU6zOJat02M1+PiuSGDziyRuI/pPue3hoUwm2uGfxdL+trT6Z9rxnlMA==", +- "cpu": [ +- "arm64" +- ], ++ "node_modules/@standard-schema/spec": { ++ "version": "1.1.0", ++ "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz", ++ "integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==", + "dev": true, +- "license": "MIT", +- "optional": true, +- "os": [ +- "linux" +- ] +- }, +- "node_modules/@rollup/rollup-linux-loong64-gnu": { +- "version": "4.60.1", +- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.60.1.tgz", +- "integrity": "sha512-VSvgvQeIcsEvY4bKDHEDWcpW4Yw7BtlKG1GUT4FzBUlEKQK0rWHYBqQt6Fm2taXS+1bXvJT6kICu5ZwqKCnvlQ==", +- "cpu": [ +- "loong64" +- ], +- "dev": true, +- "license": "MIT", +- "optional": true, +- "os": [ +- "linux" +- ] +- }, +- "node_modules/@rollup/rollup-linux-loong64-musl": { +- "version": "4.60.1", +- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.60.1.tgz", +- "integrity": "sha512-4LqhUomJqwe641gsPp6xLfhqWMbQV04KtPp7/dIp0nzPxAkNY1AbwL5W0MQpcalLYk07vaW9Kp1PBhdpZYYcEw==", +- "cpu": [ +- "loong64" +- ], +- "dev": true, +- "license": "MIT", +- "optional": true, +- "os": [ +- "linux" +- ] +- }, +- "node_modules/@rollup/rollup-linux-ppc64-gnu": { +- "version": "4.60.1", +- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.60.1.tgz", +- "integrity": "sha512-tLQQ9aPvkBxOc/EUT6j3pyeMD6Hb8QF2BTBnCQWP/uu1lhc9AIrIjKnLYMEroIz/JvtGYgI9dF3AxHZNaEH0rw==", +- "cpu": [ +- "ppc64" +- ], +- "dev": true, +- "license": "MIT", +- "optional": true, +- "os": [ +- "linux" +- ] +- }, +- "node_modules/@rollup/rollup-linux-ppc64-musl": { +- "version": "4.60.1", +- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.60.1.tgz", +- "integrity": "sha512-RMxFhJwc9fSXP6PqmAz4cbv3kAyvD1etJFjTx4ONqFP9DkTkXsAMU4v3Vyc5BgzC+anz7nS/9tp4obsKfqkDHg==", +- "cpu": [ +- "ppc64" +- ], +- "dev": true, +- "license": "MIT", +- "optional": true, +- "os": [ +- "linux" +- ] +- }, +- "node_modules/@rollup/rollup-linux-riscv64-gnu": { +- "version": "4.60.1", +- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.60.1.tgz", +- "integrity": "sha512-QKgFl+Yc1eEk6MmOBfRHYF6lTxiiiV3/z/BRrbSiW2I7AFTXoBFvdMEyglohPj//2mZS4hDOqeB0H1ACh3sBbg==", +- "cpu": [ +- "riscv64" +- ], +- "dev": true, +- "license": "MIT", +- "optional": true, +- "os": [ +- "linux" +- ] +- }, +- "node_modules/@rollup/rollup-linux-riscv64-musl": { +- "version": "4.60.1", +- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.60.1.tgz", +- "integrity": "sha512-RAjXjP/8c6ZtzatZcA1RaQr6O1TRhzC+adn8YZDnChliZHviqIjmvFwHcxi4JKPSDAt6Uhf/7vqcBzQJy0PDJg==", +- "cpu": [ +- "riscv64" +- ], +- "dev": true, +- "license": "MIT", +- "optional": true, +- "os": [ +- "linux" +- ] +- }, +- "node_modules/@rollup/rollup-linux-s390x-gnu": { +- "version": "4.60.1", +- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.60.1.tgz", +- "integrity": "sha512-wcuocpaOlaL1COBYiA89O6yfjlp3RwKDeTIA0hM7OpmhR1Bjo9j31G1uQVpDlTvwxGn2nQs65fBFL5UFd76FcQ==", +- "cpu": [ +- "s390x" +- ], +- "dev": true, +- "license": "MIT", +- "optional": true, +- "os": [ +- "linux" +- ] +- }, +- "node_modules/@rollup/rollup-linux-x64-gnu": { +- "version": "4.60.1", +- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.60.1.tgz", +- "integrity": "sha512-77PpsFQUCOiZR9+LQEFg9GClyfkNXj1MP6wRnzYs0EeWbPcHs02AXu4xuUbM1zhwn3wqaizle3AEYg5aeoohhg==", +- "cpu": [ +- "x64" +- ], +- "dev": true, +- "license": "MIT", +- "optional": true, +- "os": [ +- "linux" +- ] +- }, +- "node_modules/@rollup/rollup-linux-x64-musl": { +- "version": "4.60.1", +- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.60.1.tgz", +- "integrity": "sha512-5cIATbk5vynAjqqmyBjlciMJl1+R/CwX9oLk/EyiFXDWd95KpHdrOJT//rnUl4cUcskrd0jCCw3wpZnhIHdD9w==", +- "cpu": [ +- "x64" +- ], +- "dev": true, +- "license": "MIT", +- "optional": true, +- "os": [ +- "linux" +- ] +- }, +- "node_modules/@rollup/rollup-openbsd-x64": { +- "version": "4.60.1", +- "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.60.1.tgz", +- "integrity": "sha512-cl0w09WsCi17mcmWqqglez9Gk8isgeWvoUZ3WiJFYSR3zjBQc2J5/ihSjpl+VLjPqjQ/1hJRcqBfLjssREQILw==", +- "cpu": [ +- "x64" +- ], +- "dev": true, +- "license": "MIT", +- "optional": true, +- "os": [ +- "openbsd" +- ] +- }, +- "node_modules/@rollup/rollup-openharmony-arm64": { +- "version": "4.60.1", +- "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.60.1.tgz", +- "integrity": "sha512-4Cv23ZrONRbNtbZa37mLSueXUCtN7MXccChtKpUnQNgF010rjrjfHx3QxkS2PI7LqGT5xXyYs1a7LbzAwT0iCA==", +- "cpu": [ +- "arm64" +- ], +- "dev": true, +- "license": "MIT", +- "optional": true, +- "os": [ +- "openharmony" +- ] +- }, +- "node_modules/@rollup/rollup-win32-arm64-msvc": { +- "version": "4.60.1", +- "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.60.1.tgz", +- "integrity": "sha512-i1okWYkA4FJICtr7KpYzFpRTHgy5jdDbZiWfvny21iIKky5YExiDXP+zbXzm3dUcFpkEeYNHgQ5fuG236JPq0g==", +- "cpu": [ +- "arm64" +- ], +- "dev": true, +- "license": "MIT", +- "optional": true, +- "os": [ +- "win32" +- ] +- }, +- "node_modules/@rollup/rollup-win32-ia32-msvc": { +- "version": "4.60.1", +- "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.60.1.tgz", +- "integrity": "sha512-u09m3CuwLzShA0EYKMNiFgcjjzwqtUMLmuCJLeZWjjOYA3IT2Di09KaxGBTP9xVztWyIWjVdsB2E9goMjZvTQg==", +- "cpu": [ +- "ia32" +- ], +- "dev": true, +- "license": "MIT", +- "optional": true, +- "os": [ +- "win32" +- ] +- }, +- "node_modules/@rollup/rollup-win32-x64-gnu": { +- "version": "4.60.1", +- "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.60.1.tgz", +- "integrity": "sha512-k+600V9Zl1CM7eZxJgMyTUzmrmhB/0XZnF4pRypKAlAgxmedUA+1v9R+XOFv56W4SlHEzfeMtzujLJD22Uz5zg==", +- "cpu": [ +- "x64" +- ], +- "dev": true, +- "license": "MIT", +- "optional": true, +- "os": [ +- "win32" +- ] +- }, +- "node_modules/@rollup/rollup-win32-x64-msvc": { +- "version": "4.60.1", +- "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.60.1.tgz", +- "integrity": "sha512-lWMnixq/QzxyhTV6NjQJ4SFo1J6PvOX8vUx5Wb4bBPsEb+8xZ89Bz6kOXpfXj9ak9AHTQVQzlgzBEc1SyM27xQ==", +- "cpu": [ +- "x64" +- ], +- "dev": true, +- "license": "MIT", +- "optional": true, +- "os": [ +- "win32" +- ] ++ "license": "MIT" + }, + "node_modules/@types/chai": { + "version": "5.2.3", +@@ -1119,46 +623,47 @@ + "license": "MIT" + }, + "node_modules/@types/estree": { +- "version": "1.0.8", +- "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz", +- "integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==", ++ "version": "1.0.9", ++ "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz", ++ "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@vitest/expect": { +- "version": "3.2.4", +- "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-3.2.4.tgz", +- "integrity": "sha512-Io0yyORnB6sikFlt8QW5K7slY4OjqNX9jmJQ02QDda8lyM6B5oNgVWoSoKPac8/kgnCUzuHQKrSLtu/uOqqrig==", ++ "version": "4.1.11", ++ "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.11.tgz", ++ "integrity": "sha512-VX2x5vNJXET47KAFzwERI+KRMtTTCSWTfSMKsW7JsUsXV4psq++e3DvZpuTDOpHcxytiDs6p2nhVb2tVDiiUYw==", + "dev": true, + "license": "MIT", + "dependencies": { ++ "@standard-schema/spec": "^1.1.0", + "@types/chai": "^5.2.2", +- "@vitest/spy": "3.2.4", +- "@vitest/utils": "3.2.4", +- "chai": "^5.2.0", +- "tinyrainbow": "^2.0.0" ++ "@vitest/spy": "4.1.11", ++ "@vitest/utils": "4.1.11", ++ "chai": "^6.2.2", ++ "tinyrainbow": "^3.1.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/mocker": { +- "version": "3.2.4", +- "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-3.2.4.tgz", +- "integrity": "sha512-46ryTE9RZO/rfDd7pEqFl7etuyzekzEhUbTW3BvmeO/BcCMEgq59BKhek3dXDWgAj4oMK6OZi+vRr1wPW6qjEQ==", ++ "version": "4.1.11", ++ "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-4.1.11.tgz", ++ "integrity": "sha512-2XJVD55d1o5AZous5CCGKS74g/riOj9odEt2bQpCVZeblHyHdnMeFl4jl0XjU21stf4mbjUkew2eXQZt65g5CQ==", + "dev": true, + "license": "MIT", + "dependencies": { +- "@vitest/spy": "3.2.4", ++ "@vitest/spy": "4.1.11", + "estree-walker": "^3.0.3", +- "magic-string": "^0.30.17" ++ "magic-string": "^0.30.21" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "msw": "^2.4.9", +- "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0" ++ "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "msw": { +@@ -1170,42 +675,42 @@ + } + }, + "node_modules/@vitest/pretty-format": { +- "version": "3.2.4", +- "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-3.2.4.tgz", +- "integrity": "sha512-IVNZik8IVRJRTr9fxlitMKeJeXFFFN0JaB9PHPGQ8NKQbGpfjlTx9zO4RefN8gp7eqjNy8nyK3NZmBzOPeIxtA==", ++ "version": "4.1.11", ++ "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-4.1.11.tgz", ++ "integrity": "sha512-yiZzPbGTS9Sr/JpFl8zHrcIkAofNbFV6k21vIgQN/cY/oxZeXhJv5sc/MBJ5jFKWmWs+oJHw0UXLZjmf931+Vw==", + "dev": true, + "license": "MIT", + "dependencies": { +- "tinyrainbow": "^2.0.0" ++ "tinyrainbow": "^3.1.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/runner": { +- "version": "3.2.4", +- "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-3.2.4.tgz", +- "integrity": "sha512-oukfKT9Mk41LreEW09vt45f8wx7DordoWUZMYdY/cyAk7w5TWkTRCNZYF7sX7n2wB7jyGAl74OxgwhPgKaqDMQ==", ++ "version": "4.1.11", ++ "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-4.1.11.tgz", ++ "integrity": "sha512-LztvUgdwMNJMIkj3hQnnxiC2Xy1zNxq928W/xhjCLaNCzqTZOudjwbQf6v9IntZGPw132i2Lq2rgTRZHD3JHNw==", + "dev": true, + "license": "MIT", + "dependencies": { +- "@vitest/utils": "3.2.4", +- "pathe": "^2.0.3", +- "strip-literal": "^3.0.0" ++ "@vitest/utils": "4.1.11", ++ "pathe": "^2.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/snapshot": { +- "version": "3.2.4", +- "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-3.2.4.tgz", +- "integrity": "sha512-dEYtS7qQP2CjU27QBC5oUOxLE/v5eLkGqPE0ZKEIDGMs4vKWe7IjgLOeauHsR0D5YuuycGRO5oSRXnwnmA78fQ==", ++ "version": "4.1.11", ++ "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-4.1.11.tgz", ++ "integrity": "sha512-pN7ikn1ON7h8ee4gIAp4AzyK+zBtJPzVbqOgu5LCEh4VaJVbPQcgYQYJIMGQPXVeJJq1fnfazis7a5pFNPahog==", + "dev": true, + "license": "MIT", + "dependencies": { +- "@vitest/pretty-format": "3.2.4", +- "magic-string": "^0.30.17", ++ "@vitest/pretty-format": "4.1.11", ++ "@vitest/utils": "4.1.11", ++ "magic-string": "^0.30.21", + "pathe": "^2.0.3" + }, + "funding": { +@@ -1213,28 +718,25 @@ + } + }, + "node_modules/@vitest/spy": { +- "version": "3.2.4", +- "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-3.2.4.tgz", +- "integrity": "sha512-vAfasCOe6AIK70iP5UD11Ac4siNUNJ9i/9PZ3NKx07sG6sUxeag1LWdNrMWeKKYBLlzuK+Gn65Yd5nyL6ds+nw==", ++ "version": "4.1.11", ++ "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-4.1.11.tgz", ++ "integrity": "sha512-apNa/prQy2qCeywhnixOHPRCgGNhvg7T4Dapfl1GahLp/R+uhBm5cPyFoNVyqsNd2h1nJxL6BqqdIjiABL60YA==", + "dev": true, + "license": "MIT", +- "dependencies": { +- "tinyspy": "^4.0.3" +- }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/utils": { +- "version": "3.2.4", +- "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-3.2.4.tgz", +- "integrity": "sha512-fB2V0JFrQSMsCo9HiSq3Ezpdv4iYaXRG1Sx8edX3MwxfyNn83mKiGzOcH+Fkxt4MHxr3y42fQi1oeAInqgX2QA==", ++ "version": "4.1.11", ++ "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-4.1.11.tgz", ++ "integrity": "sha512-zTCVGpyFsGWBhllOyKlTw/vnr6D9qxsfSDyfbyZmTyjHw5N/VuvzHpHoQjm2ZJzn4RJgx5w4r7V0er69CmLgPQ==", + "dev": true, + "license": "MIT", + "dependencies": { +- "@vitest/pretty-format": "3.2.4", +- "loupe": "^3.1.4", +- "tinyrainbow": "^2.0.0" ++ "@vitest/pretty-format": "4.1.11", ++ "convert-source-map": "^2.0.0", ++ "tinyrainbow": "^3.1.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" +@@ -1307,42 +809,22 @@ + "node": ">= 10.16.0" + } + }, +- "node_modules/cac": { +- "version": "6.7.14", +- "resolved": "https://registry.npmjs.org/cac/-/cac-6.7.14.tgz", +- "integrity": "sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==", +- "dev": true, +- "license": "MIT", +- "engines": { +- "node": ">=8" +- } +- }, + "node_modules/chai": { +- "version": "5.3.3", +- "resolved": "https://registry.npmjs.org/chai/-/chai-5.3.3.tgz", +- "integrity": "sha512-4zNhdJD/iOjSH0A05ea+Ke6MU5mmpQcbQsSOkgdaUMJ9zTlDTD/GYlwohmIE2u0gaxHYiVHEn1Fw9mZ/ktJWgw==", ++ "version": "6.2.2", ++ "resolved": "https://registry.npmjs.org/chai/-/chai-6.2.2.tgz", ++ "integrity": "sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==", + "dev": true, + "license": "MIT", +- "dependencies": { +- "assertion-error": "^2.0.1", +- "check-error": "^2.1.1", +- "deep-eql": "^5.0.1", +- "loupe": "^3.1.0", +- "pathval": "^2.0.0" +- }, + "engines": { + "node": ">=18" + } + }, +- "node_modules/check-error": { +- "version": "2.1.3", +- "resolved": "https://registry.npmjs.org/check-error/-/check-error-2.1.3.tgz", +- "integrity": "sha512-PAJdDJusoxnwm1VwW07VWwUN1sl7smmC3OKggvndJFadxxDRyFJBX/ggnu/KE4kQAB7a3Dp8f/YXC1FlUprWmA==", ++ "node_modules/convert-source-map": { ++ "version": "2.0.0", ++ "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", ++ "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", + "dev": true, +- "license": "MIT", +- "engines": { +- "node": ">= 16" +- } ++ "license": "MIT" + }, + "node_modules/css-tree": { + "version": "3.2.1", +@@ -1423,14 +905,14 @@ + "dev": true, + "license": "MIT" + }, +- "node_modules/deep-eql": { +- "version": "5.0.2", +- "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-5.0.2.tgz", +- "integrity": "sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q==", ++ "node_modules/detect-libc": { ++ "version": "2.1.2", ++ "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", ++ "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "dev": true, +- "license": "MIT", ++ "license": "Apache-2.0", + "engines": { +- "node": ">=6" ++ "node": ">=8" + } + }, + "node_modules/duplexer": { +@@ -1453,9 +935,9 @@ + } + }, + "node_modules/es-module-lexer": { +- "version": "1.7.0", +- "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-1.7.0.tgz", +- "integrity": "sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==", ++ "version": "2.3.2", ++ "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.2.tgz", ++ "integrity": "sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==", + "dev": true, + "license": "MIT" + }, +@@ -1959,13 +1441,6 @@ + "dev": true, + "license": "MIT" + }, +- "node_modules/js-tokens": { +- "version": "9.0.1", +- "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-9.0.1.tgz", +- "integrity": "sha512-mxa9E9ITFOt0ban3j6L5MpjwegGz6lBQmM1IJkWeBZGcMxto50+eWdjC/52xDbS2vy0k7vIMK0Fe2wfL9OQSpQ==", +- "dev": true, +- "license": "MIT" +- }, + "node_modules/jsdom": { + "version": "27.0.0", + "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-27.0.0.tgz", +@@ -2006,12 +1481,266 @@ + } + } + }, +- "node_modules/loupe": { +- "version": "3.2.1", +- "resolved": "https://registry.npmjs.org/loupe/-/loupe-3.2.1.tgz", +- "integrity": "sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ==", ++ "node_modules/lightningcss": { ++ "version": "1.33.0", ++ "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz", ++ "integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==", + "dev": true, +- "license": "MIT" ++ "license": "MPL-2.0", ++ "dependencies": { ++ "detect-libc": "^2.0.3" ++ }, ++ "engines": { ++ "node": ">= 12.0.0" ++ }, ++ "funding": { ++ "type": "opencollective", ++ "url": "https://opencollective.com/parcel" ++ }, ++ "optionalDependencies": { ++ "lightningcss-android-arm64": "1.33.0", ++ "lightningcss-darwin-arm64": "1.33.0", ++ "lightningcss-darwin-x64": "1.33.0", ++ "lightningcss-freebsd-x64": "1.33.0", ++ "lightningcss-linux-arm-gnueabihf": "1.33.0", ++ "lightningcss-linux-arm64-gnu": "1.33.0", ++ "lightningcss-linux-arm64-musl": "1.33.0", ++ "lightningcss-linux-x64-gnu": "1.33.0", ++ "lightningcss-linux-x64-musl": "1.33.0", ++ "lightningcss-win32-arm64-msvc": "1.33.0", ++ "lightningcss-win32-x64-msvc": "1.33.0" ++ } ++ }, ++ "node_modules/lightningcss-android-arm64": { ++ "version": "1.33.0", ++ "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.33.0.tgz", ++ "integrity": "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==", ++ "cpu": [ ++ "arm64" ++ ], ++ "dev": true, ++ "license": "MPL-2.0", ++ "optional": true, ++ "os": [ ++ "android" ++ ], ++ "engines": { ++ "node": ">= 12.0.0" ++ }, ++ "funding": { ++ "type": "opencollective", ++ "url": "https://opencollective.com/parcel" ++ } ++ }, ++ "node_modules/lightningcss-darwin-arm64": { ++ "version": "1.33.0", ++ "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.33.0.tgz", ++ "integrity": "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==", ++ "cpu": [ ++ "arm64" ++ ], ++ "dev": true, ++ "license": "MPL-2.0", ++ "optional": true, ++ "os": [ ++ "darwin" ++ ], ++ "engines": { ++ "node": ">= 12.0.0" ++ }, ++ "funding": { ++ "type": "opencollective", ++ "url": "https://opencollective.com/parcel" ++ } ++ }, ++ "node_modules/lightningcss-darwin-x64": { ++ "version": "1.33.0", ++ "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.33.0.tgz", ++ "integrity": "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==", ++ "cpu": [ ++ "x64" ++ ], ++ "dev": true, ++ "license": "MPL-2.0", ++ "optional": true, ++ "os": [ ++ "darwin" ++ ], ++ "engines": { ++ "node": ">= 12.0.0" ++ }, ++ "funding": { ++ "type": "opencollective", ++ "url": "https://opencollective.com/parcel" ++ } ++ }, ++ "node_modules/lightningcss-freebsd-x64": { ++ "version": "1.33.0", ++ "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.33.0.tgz", ++ "integrity": "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==", ++ "cpu": [ ++ "x64" ++ ], ++ "dev": true, ++ "license": "MPL-2.0", ++ "optional": true, ++ "os": [ ++ "freebsd" ++ ], ++ "engines": { ++ "node": ">= 12.0.0" ++ }, ++ "funding": { ++ "type": "opencollective", ++ "url": "https://opencollective.com/parcel" ++ } ++ }, ++ "node_modules/lightningcss-linux-arm-gnueabihf": { ++ "version": "1.33.0", ++ "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.33.0.tgz", ++ "integrity": "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==", ++ "cpu": [ ++ "arm" ++ ], ++ "dev": true, ++ "license": "MPL-2.0", ++ "optional": true, ++ "os": [ ++ "linux" ++ ], ++ "engines": { ++ "node": ">= 12.0.0" ++ }, ++ "funding": { ++ "type": "opencollective", ++ "url": "https://opencollective.com/parcel" ++ } ++ }, ++ "node_modules/lightningcss-linux-arm64-gnu": { ++ "version": "1.33.0", ++ "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.33.0.tgz", ++ "integrity": "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==", ++ "cpu": [ ++ "arm64" ++ ], ++ "dev": true, ++ "license": "MPL-2.0", ++ "optional": true, ++ "os": [ ++ "linux" ++ ], ++ "engines": { ++ "node": ">= 12.0.0" ++ }, ++ "funding": { ++ "type": "opencollective", ++ "url": "https://opencollective.com/parcel" ++ } ++ }, ++ "node_modules/lightningcss-linux-arm64-musl": { ++ "version": "1.33.0", ++ "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.33.0.tgz", ++ "integrity": "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==", ++ "cpu": [ ++ "arm64" ++ ], ++ "dev": true, ++ "license": "MPL-2.0", ++ "optional": true, ++ "os": [ ++ "linux" ++ ], ++ "engines": { ++ "node": ">= 12.0.0" ++ }, ++ "funding": { ++ "type": "opencollective", ++ "url": "https://opencollective.com/parcel" ++ } ++ }, ++ "node_modules/lightningcss-linux-x64-gnu": { ++ "version": "1.33.0", ++ "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.33.0.tgz", ++ "integrity": "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==", ++ "cpu": [ ++ "x64" ++ ], ++ "dev": true, ++ "license": "MPL-2.0", ++ "optional": true, ++ "os": [ ++ "linux" ++ ], ++ "engines": { ++ "node": ">= 12.0.0" ++ }, ++ "funding": { ++ "type": "opencollective", ++ "url": "https://opencollective.com/parcel" ++ } ++ }, ++ "node_modules/lightningcss-linux-x64-musl": { ++ "version": "1.33.0", ++ "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.33.0.tgz", ++ "integrity": "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==", ++ "cpu": [ ++ "x64" ++ ], ++ "dev": true, ++ "license": "MPL-2.0", ++ "optional": true, ++ "os": [ ++ "linux" ++ ], ++ "engines": { ++ "node": ">= 12.0.0" ++ }, ++ "funding": { ++ "type": "opencollective", ++ "url": "https://opencollective.com/parcel" ++ } ++ }, ++ "node_modules/lightningcss-win32-arm64-msvc": { ++ "version": "1.33.0", ++ "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.33.0.tgz", ++ "integrity": "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==", ++ "cpu": [ ++ "arm64" ++ ], ++ "dev": true, ++ "license": "MPL-2.0", ++ "optional": true, ++ "os": [ ++ "win32" ++ ], ++ "engines": { ++ "node": ">= 12.0.0" ++ }, ++ "funding": { ++ "type": "opencollective", ++ "url": "https://opencollective.com/parcel" ++ } ++ }, ++ "node_modules/lightningcss-win32-x64-msvc": { ++ "version": "1.33.0", ++ "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.33.0.tgz", ++ "integrity": "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==", ++ "cpu": [ ++ "x64" ++ ], ++ "dev": true, ++ "license": "MPL-2.0", ++ "optional": true, ++ "os": [ ++ "win32" ++ ], ++ "engines": { ++ "node": ">= 12.0.0" ++ }, ++ "funding": { ++ "type": "opencollective", ++ "url": "https://opencollective.com/parcel" ++ } + }, + "node_modules/lru-cache": { + "version": "11.2.7", +@@ -2072,6 +1801,20 @@ + "integrity": "sha512-I19aIingLgR1fmhftnbWWO3dXc0hSxqHQHQb3H8m+K3TnEn/iSeTZZOyvKXWqQESMwuUVnatlCnZdLBZZt2VSA==", + "license": "MIT" + }, ++ "node_modules/obug": { ++ "version": "2.2.1", ++ "resolved": "https://registry.npmjs.org/obug/-/obug-2.2.1.tgz", ++ "integrity": "sha512-XrsrhT5sybtKI6wakr2SPOlGZWWYbUXZ7a0jT8/QOeAPau+1X/bSegNe5YR75oJmEZQbKningirmGOEJCIk61Q==", ++ "dev": true, ++ "funding": [ ++ "https://github.com/sponsors/sxzz", ++ "https://opencollective.com/debug" ++ ], ++ "license": "MIT", ++ "engines": { ++ "node": ">=12.20.0" ++ } ++ }, + "node_modules/parse5": { + "version": "7.3.0", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-7.3.0.tgz", +@@ -2092,16 +1835,6 @@ + "dev": true, + "license": "MIT" + }, +- "node_modules/pathval": { +- "version": "2.0.1", +- "resolved": "https://registry.npmjs.org/pathval/-/pathval-2.0.1.tgz", +- "integrity": "sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ==", +- "dev": true, +- "license": "MIT", +- "engines": { +- "node": ">= 14.16" +- } +- }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", +@@ -2110,9 +1843,9 @@ + "license": "ISC" + }, + "node_modules/picomatch": { +- "version": "4.0.4", +- "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz", +- "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==", ++ "version": "4.0.7", ++ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", ++ "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", + "dev": true, + "license": "MIT", + "engines": { +@@ -2123,9 +1856,9 @@ + } + }, + "node_modules/postcss": { +- "version": "8.5.26", +- "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.26.tgz", +- "integrity": "sha512-u82N74LFzG8ca+dD8puPnplTXoGH4fTPpVGuIbt36G3qvNlkvfD0lEAZSxaly3KX8TS/L1A1gsCEmvKmBcVbkQ==", ++ "version": "8.5.28", ++ "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.28.tgz", ++ "integrity": "sha512-RRuzqDtt5Y9h3quz5hWhK+TPnsmVs6WwSU6LkJMeY4HstUEDuYTG8UJSdawMRzmzAtV+KEoG8N3Qg2qLy5vM/A==", + "dev": true, + "funding": [ + { +@@ -2143,7 +1876,7 @@ + ], + "license": "MIT", + "dependencies": { +- "nanoid": "^3.3.17", ++ "nanoid": "^3.3.18", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.1" + }, +@@ -2171,49 +1904,38 @@ + "node": ">=0.10.0" + } + }, +- "node_modules/rollup": { +- "version": "4.60.1", +- "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.60.1.tgz", +- "integrity": "sha512-VmtB2rFU/GroZ4oL8+ZqXgSA38O6GR8KSIvWmEFv63pQ0G6KaBH9s07PO8XTXP4vI+3UJUEypOfjkGfmSBBR0w==", ++ "node_modules/rolldown": { ++ "version": "1.2.8", ++ "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.8.tgz", ++ "integrity": "sha512-Z67nTmhZe7anqnM/EjI392w5i/ANUinjip7QYsOyN37oayduxt3ksdX0hf5OOamkAd53BiIHfbfSzfUmzKFQqQ==", + "dev": true, + "license": "MIT", + "dependencies": { +- "@types/estree": "1.0.8" ++ "@oxc-project/types": "=0.149.0", ++ "@rolldown/pluginutils": "^1.0.0" + }, + "bin": { +- "rollup": "dist/bin/rollup" ++ "rolldown": "bin/cli.mjs" + }, + "engines": { +- "node": ">=18.0.0", +- "npm": ">=8.0.0" ++ "node": "^20.19.0 || >=22.12.0" + }, + "optionalDependencies": { +- "@rollup/rollup-android-arm-eabi": "4.60.1", +- "@rollup/rollup-android-arm64": "4.60.1", +- "@rollup/rollup-darwin-arm64": "4.60.1", +- "@rollup/rollup-darwin-x64": "4.60.1", +- "@rollup/rollup-freebsd-arm64": "4.60.1", +- "@rollup/rollup-freebsd-x64": "4.60.1", +- "@rollup/rollup-linux-arm-gnueabihf": "4.60.1", +- "@rollup/rollup-linux-arm-musleabihf": "4.60.1", +- "@rollup/rollup-linux-arm64-gnu": "4.60.1", +- "@rollup/rollup-linux-arm64-musl": "4.60.1", +- "@rollup/rollup-linux-loong64-gnu": "4.60.1", +- "@rollup/rollup-linux-loong64-musl": "4.60.1", +- "@rollup/rollup-linux-ppc64-gnu": "4.60.1", +- "@rollup/rollup-linux-ppc64-musl": "4.60.1", +- "@rollup/rollup-linux-riscv64-gnu": "4.60.1", +- "@rollup/rollup-linux-riscv64-musl": "4.60.1", +- "@rollup/rollup-linux-s390x-gnu": "4.60.1", +- "@rollup/rollup-linux-x64-gnu": "4.60.1", +- "@rollup/rollup-linux-x64-musl": "4.60.1", +- "@rollup/rollup-openbsd-x64": "4.60.1", +- "@rollup/rollup-openharmony-arm64": "4.60.1", +- "@rollup/rollup-win32-arm64-msvc": "4.60.1", +- "@rollup/rollup-win32-ia32-msvc": "4.60.1", +- "@rollup/rollup-win32-x64-gnu": "4.60.1", +- "@rollup/rollup-win32-x64-msvc": "4.60.1", +- "fsevents": "~2.3.2" ++ "@rolldown/binding-android-arm-eabi": "1.2.8", ++ "@rolldown/binding-android-arm64": "1.2.8", ++ "@rolldown/binding-darwin-arm64": "1.2.8", ++ "@rolldown/binding-darwin-x64": "1.2.8", ++ "@rolldown/binding-freebsd-x64": "1.2.8", ++ "@rolldown/binding-linux-arm-gnueabihf": "1.2.8", ++ "@rolldown/binding-linux-arm64-gnu": "1.2.8", ++ "@rolldown/binding-linux-arm64-musl": "1.2.8", ++ "@rolldown/binding-linux-ppc64-gnu": "1.2.8", ++ "@rolldown/binding-linux-s390x-gnu": "1.2.8", ++ "@rolldown/binding-linux-x64-gnu": "1.2.8", ++ "@rolldown/binding-linux-x64-musl": "1.2.8", ++ "@rolldown/binding-openharmony-arm64": "1.2.8", ++ "@rolldown/binding-win32-arm64-msvc": "1.2.8", ++ "@rolldown/binding-win32-x64-msvc": "1.2.8" + } + }, + "node_modules/rrweb-cssom": { +@@ -2274,25 +1996,12 @@ + "license": "MIT" + }, + "node_modules/std-env": { +- "version": "3.10.0", +- "resolved": "https://registry.npmjs.org/std-env/-/std-env-3.10.0.tgz", +- "integrity": "sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==", ++ "version": "4.2.0", ++ "resolved": "https://registry.npmjs.org/std-env/-/std-env-4.2.0.tgz", ++ "integrity": "sha512-oCUKSupKTHX53EyjDtuZQ64pjLJ6yYCtpmEw0goYxtjG9KpbRe8KAsl2tBUGU9DyMcJ0RwJ8GqJAFzMXcXW1Rw==", + "dev": true, + "license": "MIT" + }, +- "node_modules/strip-literal": { +- "version": "3.1.0", +- "resolved": "https://registry.npmjs.org/strip-literal/-/strip-literal-3.1.0.tgz", +- "integrity": "sha512-8r3mkIM/2+PpjHoOtiAW8Rg3jJLHaV7xPwG+YRGrv6FP0wwk/toTpATxWYOW0BKdWwl82VT2tFYi5DlROa0Mxg==", +- "dev": true, +- "license": "MIT", +- "dependencies": { +- "js-tokens": "^9.0.1" +- }, +- "funding": { +- "url": "https://github.com/sponsors/antfu" +- } +- }, + "node_modules/symbol-tree": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz", +@@ -2314,21 +2023,24 @@ + "license": "MIT" + }, + "node_modules/tinyexec": { +- "version": "0.3.2", +- "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-0.3.2.tgz", +- "integrity": "sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA==", ++ "version": "1.3.1", ++ "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.3.1.tgz", ++ "integrity": "sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA==", + "dev": true, +- "license": "MIT" ++ "license": "MIT", ++ "engines": { ++ "node": ">=18" ++ } + }, + "node_modules/tinyglobby": { +- "version": "0.2.15", +- "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz", +- "integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==", ++ "version": "0.2.17", ++ "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", ++ "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", +- "picomatch": "^4.0.3" ++ "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" +@@ -2337,30 +2049,10 @@ + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, +- "node_modules/tinypool": { +- "version": "1.1.1", +- "resolved": "https://registry.npmjs.org/tinypool/-/tinypool-1.1.1.tgz", +- "integrity": "sha512-Zba82s87IFq9A9XmjiX5uZA/ARWDrB03OHlq+Vw1fSdt0I+4/Kutwy8BP4Y/y/aORMo61FQ0vIb5j44vSo5Pkg==", +- "dev": true, +- "license": "MIT", +- "engines": { +- "node": "^18.0.0 || >=20.0.0" +- } +- }, + "node_modules/tinyrainbow": { +- "version": "2.0.0", +- "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-2.0.0.tgz", +- "integrity": "sha512-op4nsTR47R6p0vMUUoYl/a+ljLFVtlfaXkLQmqfLR1qHma1h/ysYk4hEXZ880bf2CYgTskvTa/e196Vd5dDQXw==", +- "dev": true, +- "license": "MIT", +- "engines": { +- "node": ">=14.0.0" +- } +- }, +- "node_modules/tinyspy": { +- "version": "4.0.4", +- "resolved": "https://registry.npmjs.org/tinyspy/-/tinyspy-4.0.4.tgz", +- "integrity": "sha512-azl+t0z7pw/z958Gy9svOTuzqIk6xq+NSheJzn5MMWtWTFywIacg2wUlzKFGtt3cthx0r2SxMK0yzJOR0IES7Q==", ++ "version": "3.1.1", ++ "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-3.1.1.tgz", ++ "integrity": "sha512-yau8yJdTt989Mm0Bd/236QnzEiPf2xLLTqUZRUJOo/3CB078LSwzei343DgtJVmfJKJE3TMINY1u42SQsP6mXw==", + "dev": true, + "license": "MIT", + "engines": { +@@ -2414,18 +2106,17 @@ + } + }, + "node_modules/vite": { +- "version": "7.3.1", +- "resolved": "https://registry.npmjs.org/vite/-/vite-7.3.1.tgz", +- "integrity": "sha512-w+N7Hifpc3gRjZ63vYBXA56dvvRlNWRczTdmCBBa+CotUzAPf5b7YMdMR/8CQoeYE5LX3W4wj6RYTgonm1b9DA==", ++ "version": "8.3.0", ++ "resolved": "https://registry.npmjs.org/vite/-/vite-8.3.0.tgz", ++ "integrity": "sha512-lhZBVvEHefgE+HQZC9O7EBJgCU/nVzFNl7vkS4RE0APtWLP02/8QVIkQtzBxPquh7lq5/78NHipTj7ODQ6XuyQ==", + "dev": true, + "license": "MIT", + "dependencies": { +- "esbuild": "^0.27.0", +- "fdir": "^6.5.0", +- "picomatch": "^4.0.3", +- "postcss": "^8.5.6", +- "rollup": "^4.43.0", +- "tinyglobby": "^0.2.15" ++ "lightningcss": "^1.33.0", ++ "picomatch": "^4.0.7", ++ "postcss": "^8.5.28", ++ "rolldown": "~1.2.6", ++ "tinyglobby": "^0.2.17" + }, + "bin": { + "vite": "bin/vite.js" +@@ -2441,9 +2132,10 @@ + }, + "peerDependencies": { + "@types/node": "^20.19.0 || >=22.12.0", ++ "@vitejs/devtools": "^0.7.1", ++ "esbuild": "^0.27.0 || ^0.28.0", + "jiti": ">=1.21.0", + "less": "^4.0.0", +- "lightningcss": "^1.21.0", + "sass": "^1.70.0", + "sass-embedded": "^1.70.0", + "stylus": ">=0.54.8", +@@ -2456,13 +2148,16 @@ + "@types/node": { + "optional": true + }, +- "jiti": { ++ "@vitejs/devtools": { + "optional": true + }, +- "less": { ++ "esbuild": { + "optional": true + }, +- "lightningcss": { ++ "jiti": { ++ "optional": true ++ }, ++ "less": { + "optional": true + }, + "sass": { +@@ -2488,148 +2183,80 @@ + } + } + }, +- "node_modules/vite-node": { +- "version": "3.2.4", +- "resolved": "https://registry.npmjs.org/vite-node/-/vite-node-3.2.4.tgz", +- "integrity": "sha512-EbKSKh+bh1E1IFxeO0pg1n4dvoOTt0UDiXMd/qn++r98+jPO1xtJilvXldeuQ8giIB5IkpjCgMleHMNEsGH6pg==", +- "dev": true, +- "license": "MIT", +- "dependencies": { +- "cac": "^6.7.14", +- "debug": "^4.4.1", +- "es-module-lexer": "^1.7.0", +- "pathe": "^2.0.3", +- "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0" +- }, +- "bin": { +- "vite-node": "vite-node.mjs" +- }, +- "engines": { +- "node": "^18.0.0 || ^20.0.0 || >=22.0.0" +- }, +- "funding": { +- "url": "https://opencollective.com/vitest" +- } +- }, +- "node_modules/vite/node_modules/@esbuild/linux-loong64": { +- "version": "0.27.4", +- "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.27.4.tgz", +- "integrity": "sha512-8mL/vh8qeCoRcFH2nM8wm5uJP+ZcVYGGayMavi8GmRJjuI3g1v6Z7Ni0JJKAJW+m0EtUuARb6Lmp4hMjzCBWzA==", +- "cpu": [ +- "loong64" +- ], +- "dev": true, +- "license": "MIT", +- "optional": true, +- "os": [ +- "linux" +- ], +- "engines": { +- "node": ">=18" +- } +- }, +- "node_modules/vite/node_modules/esbuild": { +- "version": "0.27.4", +- "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.27.4.tgz", +- "integrity": "sha512-Rq4vbHnYkK5fws5NF7MYTU68FPRE1ajX7heQ/8QXXWqNgqqJ/GkmmyxIzUnf2Sr/bakf8l54716CcMGHYhMrrQ==", +- "dev": true, +- "hasInstallScript": true, +- "license": "MIT", +- "bin": { +- "esbuild": "bin/esbuild" +- }, +- "engines": { +- "node": ">=18" +- }, +- "optionalDependencies": { +- "@esbuild/aix-ppc64": "0.27.4", +- "@esbuild/android-arm": "0.27.4", +- "@esbuild/android-arm64": "0.27.4", +- "@esbuild/android-x64": "0.27.4", +- "@esbuild/darwin-arm64": "0.27.4", +- "@esbuild/darwin-x64": "0.27.4", +- "@esbuild/freebsd-arm64": "0.27.4", +- "@esbuild/freebsd-x64": "0.27.4", +- "@esbuild/linux-arm": "0.27.4", +- "@esbuild/linux-arm64": "0.27.4", +- "@esbuild/linux-ia32": "0.27.4", +- "@esbuild/linux-loong64": "0.27.4", +- "@esbuild/linux-mips64el": "0.27.4", +- "@esbuild/linux-ppc64": "0.27.4", +- "@esbuild/linux-riscv64": "0.27.4", +- "@esbuild/linux-s390x": "0.27.4", +- "@esbuild/linux-x64": "0.27.4", +- "@esbuild/netbsd-arm64": "0.27.4", +- "@esbuild/netbsd-x64": "0.27.4", +- "@esbuild/openbsd-arm64": "0.27.4", +- "@esbuild/openbsd-x64": "0.27.4", +- "@esbuild/openharmony-arm64": "0.27.4", +- "@esbuild/sunos-x64": "0.27.4", +- "@esbuild/win32-arm64": "0.27.4", +- "@esbuild/win32-ia32": "0.27.4", +- "@esbuild/win32-x64": "0.27.4" +- } +- }, + "node_modules/vitest": { +- "version": "3.2.4", +- "resolved": "https://registry.npmjs.org/vitest/-/vitest-3.2.4.tgz", +- "integrity": "sha512-LUCP5ev3GURDysTWiP47wRRUpLKMOfPh+yKTx3kVIEiu5KOMeqzpnYNsKyOoVrULivR8tLcks4+lga33Whn90A==", ++ "version": "4.1.11", ++ "resolved": "https://registry.npmjs.org/vitest/-/vitest-4.1.11.tgz", ++ "integrity": "sha512-fhACrNXUidIbGSBr5FlbuBkO7VWC1ZyLl0DO4CU2DrQoAPxX84Ysxs+HeGQpii5lZWV1Q4gBZTTu49mF+A6Edw==", + "dev": true, + "license": "MIT", + "dependencies": { +- "@types/chai": "^5.2.2", +- "@vitest/expect": "3.2.4", +- "@vitest/mocker": "3.2.4", +- "@vitest/pretty-format": "^3.2.4", +- "@vitest/runner": "3.2.4", +- "@vitest/snapshot": "3.2.4", +- "@vitest/spy": "3.2.4", +- "@vitest/utils": "3.2.4", +- "chai": "^5.2.0", +- "debug": "^4.4.1", +- "expect-type": "^1.2.1", +- "magic-string": "^0.30.17", ++ "@vitest/expect": "4.1.11", ++ "@vitest/mocker": "4.1.11", ++ "@vitest/pretty-format": "4.1.11", ++ "@vitest/runner": "4.1.11", ++ "@vitest/snapshot": "4.1.11", ++ "@vitest/spy": "4.1.11", ++ "@vitest/utils": "4.1.11", ++ "es-module-lexer": "^2.0.0", ++ "expect-type": "^1.3.0", ++ "magic-string": "^0.30.21", ++ "obug": "^2.1.1", + "pathe": "^2.0.3", +- "picomatch": "^4.0.2", +- "std-env": "^3.9.0", ++ "picomatch": "^4.0.3", ++ "std-env": "^4.0.0-rc.1", + "tinybench": "^2.9.0", +- "tinyexec": "^0.3.2", +- "tinyglobby": "^0.2.14", +- "tinypool": "^1.1.1", +- "tinyrainbow": "^2.0.0", +- "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0", +- "vite-node": "3.2.4", ++ "tinyexec": "^1.0.2", ++ "tinyglobby": "^0.2.15", ++ "tinyrainbow": "^3.1.0", ++ "vite": "^6.0.0 || ^7.0.0 || ^8.0.0", + "why-is-node-running": "^2.3.0" + }, + "bin": { + "vitest": "vitest.mjs" + }, + "engines": { +- "node": "^18.0.0 || ^20.0.0 || >=22.0.0" ++ "node": "^20.0.0 || ^22.0.0 || >=24.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@edge-runtime/vm": "*", +- "@types/debug": "^4.1.12", +- "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", +- "@vitest/browser": "3.2.4", +- "@vitest/ui": "3.2.4", ++ "@opentelemetry/api": "^1.9.0", ++ "@types/node": "^20.0.0 || ^22.0.0 || >=24.0.0", ++ "@vitest/browser-playwright": "4.1.11", ++ "@vitest/browser-preview": "4.1.11", ++ "@vitest/browser-webdriverio": "4.1.11", ++ "@vitest/coverage-istanbul": "4.1.11", ++ "@vitest/coverage-v8": "4.1.11", ++ "@vitest/ui": "4.1.11", + "happy-dom": "*", +- "jsdom": "*" ++ "jsdom": "*", ++ "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "@edge-runtime/vm": { + "optional": true + }, +- "@types/debug": { ++ "@opentelemetry/api": { + "optional": true + }, + "@types/node": { + "optional": true + }, +- "@vitest/browser": { ++ "@vitest/browser-playwright": { ++ "optional": true ++ }, ++ "@vitest/browser-preview": { ++ "optional": true ++ }, ++ "@vitest/browser-webdriverio": { ++ "optional": true ++ }, ++ "@vitest/coverage-istanbul": { ++ "optional": true ++ }, ++ "@vitest/coverage-v8": { + "optional": true + }, + "@vitest/ui": { +@@ -2640,6 +2267,9 @@ + }, + "jsdom": { + "optional": true ++ }, ++ "vite": { ++ "optional": false + } + } + }, +diff --git a/package.json b/package.json +index 89ae6989..fd0c48b7 100644 +--- a/package.json ++++ b/package.json +@@ -14,7 +14,7 @@ + "brotli-size": "^4.0.0", + "esbuild": "^0.14.49", + "jsdom": "27.0.0", +- "vitest": "^3.2.4" ++ "vitest": "^4.1.11" + }, + "dependencies": { + "@alpinejs/anchor": "^3.17.2", diff --git a/tasks/livewire__livewire-10697/tests/test.sh b/tasks/livewire__livewire-10697/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..d9e104ac10ce04afb00a3ea9d4a390a83a77d23b --- /dev/null +++ b/tasks/livewire__livewire-10697/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 31b12dd0f4b44bfa9a5c2fb3d13dd93ad35dad3f > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/livewire__livewire-10697/tests/verifier.py b/tasks/livewire__livewire-10697/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/livewire__livewire-10697/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/livewire__livewire-10701/environment/Dockerfile b/tasks/livewire__livewire-10701/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cd37b2f186515ea7c15437a68e38226a3156d74d --- /dev/null +++ b/tasks/livewire__livewire-10701/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/livewire/livewire.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/livewire/livewire.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/livewire/livewire.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 6d0cdec2e34b060e56e7d6020dc47a9852320eb7 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 6d0cdec2e34b060e56e7d6020dc47a9852320eb7 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 6d0cdec2e34b060e56e7d6020dc47a9852320eb7 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/livewire__livewire-10701/instruction.md b/tasks/livewire__livewire-10701/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c737ff9f9cca97247d47ff20d200e666fb1e03e2 --- /dev/null +++ b/tasks/livewire__livewire-10701/instruction.md @@ -0,0 +1,17 @@ +# Issue + +**Title:** Backport navigate fragment scrolling to 3.x + +## Description + +Backports the compatible fragment-scroll fix from #10692 to 3.x. + +The one branch-specific conflict retained the established 3.x wire:scroll selector while adding the same fragment target lookup and history-restoration guard. + +Local verification: +- Production asset build passed. +- All 4 focused real-browser regression tests passed with 16 assertions. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `6d0cdec2e34b`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10701/solution/patch.diff b/tasks/livewire__livewire-10701/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..b75361443dc7d35fab6e72434155b20836de9df2 --- /dev/null +++ b/tasks/livewire__livewire-10701/solution/patch.diff @@ -0,0 +1,133 @@ +diff --git a/js/plugins/navigate/scroll.js b/js/plugins/navigate/scroll.js +index ecabbfab..5affa716 100644 +--- a/js/plugins/navigate/scroll.js ++++ b/js/plugins/navigate/scroll.js +@@ -26,9 +26,34 @@ export function restoreScrollPositionOrScrollToTop() { + + queueMicrotask(() => { + queueMicrotask(() => { // Double microtask here to make sure scrolling restoration is the LAST thing to happen. (Even after Alpine's x-init functions)... ++ let shouldScrollToFragment = ! document.body.hasAttribute('data-scroll-x') ++ + scroll(document.body) + + document.querySelectorAll(['[x-navigate\\:scroll]', '[wire\\:scroll]']).forEach(scroll) ++ ++ if (shouldScrollToFragment) { ++ getFragmentTarget()?.scrollIntoView({ behavior: 'instant' }) ++ } + }) + }) + } ++ ++function getFragmentTarget() { ++ let fragment = window.location.hash.substring(1) ++ ++ if (! fragment) return ++ ++ let target = document.getElementById(fragment) ++ ++ if (target) return target ++ ++ try { ++ fragment = decodeURIComponent(fragment) ++ } catch (e) { ++ // A malformed escape sequence can still be a valid element ID or name. ++ } ++ ++ return document.getElementById(fragment) ++ || Array.from(document.getElementsByName(fragment)).find(el => el.tagName === 'A') ++} +diff --git a/src/Features/SupportNavigate/BrowserTest.php b/src/Features/SupportNavigate/BrowserTest.php +index 1610f12d..725cb5fe 100644 +--- a/src/Features/SupportNavigate/BrowserTest.php ++++ b/src/Features/SupportNavigate/BrowserTest.php +@@ -646,6 +646,60 @@ class BrowserTest extends \Tests\BrowserTestCase + }); + } + ++ public function test_navigate_scrolls_to_fragment_targets() ++ { ++ $this->browse(function ($browser) { ++ foreach (['comments', 'comments%3Areplies', '100%', 'legacy-comments'] as $index => $fragment) { ++ $browser ++ ->visit('/first-scroll') ++ ->waitForNavigate()->click('@link.to.fragment.'.$index) ++ ->assertFragmentIs($fragment) ++ ->assertInViewPort('@second-target'); ++ } ++ }); ++ } ++ ++ public function test_navigate_with_an_unknown_fragment_scrolls_to_top() ++ { ++ $this->browse(function ($browser) { ++ $browser ++ ->visit('/first-scroll') ++ ->waitForNavigate()->click('@link.to.fragment.4') ++ ->assertFragmentIs('missing') ++ ->assertScript('window.scrollY', 0); ++ }); ++ } ++ ++ public function test_navigate_fragment_does_not_override_history_scroll_restoration() ++ { ++ $this->browse(function ($browser) { ++ $browser ++ ->visit('/first-scroll') ++ ->waitForNavigate()->click('@link.to.fragment.0') ++ ->assertInViewPort('@second-target'); ++ ++ $browser->script('window.scrollTo(0, 0)'); ++ ++ $browser ++ ->assertScript('window.scrollY', 0) ++ ->waitForNavigate()->back() ++ ->waitForNavigate()->forward() ++ ->assertFragmentIs('comments') ++ ->assertScript('window.scrollY', 0); ++ }); ++ } ++ ++ public function test_navigate_fragment_respects_preserve_scroll() ++ { ++ $this->browse(function ($browser) { ++ $browser ++ ->visit('/first-scroll') ++ ->waitForNavigate()->click('@link.to.fragment.with.preserve.scroll') ++ ->assertFragmentIs('comments') ++ ->assertScript('window.scrollY', 0); ++ }); ++ } ++ + public function test_navigate_scrolls_to_top_and_back_preserves_scroll() + { + $this->browse(function ($browser) { +@@ -1631,6 +1685,14 @@ class FirstScrollPage extends Component +
+
On first
+ ++
++ Preserve scroll ++ ++ @foreach (['comments', 'comments%3Areplies', '100%', 'legacy-comments', 'missing'] as $fragment) ++ Go to fragment ++ @endforeach ++
++ +
spacer
+ +
below the fold
+@@ -1696,7 +1758,12 @@ class SecondScrollPage extends Component + +
spacer
+ +-
below the fold
++
++ Replies ++ Percentage ++ Legacy comments ++ below the fold ++
+ +
spacer
+
diff --git a/tasks/livewire__livewire-10701/solution/solve.sh b/tasks/livewire__livewire-10701/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/livewire__livewire-10701/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/livewire__livewire-10701/task.toml b/tasks/livewire__livewire-10701/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..2d190fb17a135fd4700801861bba1895e1663e83 --- /dev/null +++ b/tasks/livewire__livewire-10701/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/livewire__livewire-10701" +description = "Backport navigate fragment scrolling to 3.x" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "livewire", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "livewire/livewire" +ref = "6d0cdec2e34b060e56e7d6020dc47a9852320eb7" +reference = "https://github.com/livewire/livewire/pull/10701" +source_access = "auto" +built_at = "2026-11-16T16:09:51.489128+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:eb00e93c5cbab1fa47fd4b159ff503b671da3a3bab27a50874c331d6bf17895a" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-14T16:32:25Z" +diff_format = "unified" +context_files = [ + "js/plugins/navigate/scroll.js", + "src/Features/SupportNavigate/BrowserTest.php", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 94 +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.413418+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:073911788590bc0929f73e5b9dffc975fdefc148f543a7ed831118efb5763594" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/livewire__livewire-10701/tests/capture.py b/tasks/livewire__livewire-10701/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/livewire__livewire-10701/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/livewire__livewire-10701/tests/instruction.md b/tasks/livewire__livewire-10701/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c737ff9f9cca97247d47ff20d200e666fb1e03e2 --- /dev/null +++ b/tasks/livewire__livewire-10701/tests/instruction.md @@ -0,0 +1,17 @@ +# Issue + +**Title:** Backport navigate fragment scrolling to 3.x + +## Description + +Backports the compatible fragment-scroll fix from #10692 to 3.x. + +The one branch-specific conflict retained the established 3.x wire:scroll selector while adding the same fragment target lookup and history-restoration guard. + +Local verification: +- Production asset build passed. +- All 4 focused real-browser regression tests passed with 16 assertions. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `6d0cdec2e34b`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10701/tests/oracle.patch b/tasks/livewire__livewire-10701/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..b75361443dc7d35fab6e72434155b20836de9df2 --- /dev/null +++ b/tasks/livewire__livewire-10701/tests/oracle.patch @@ -0,0 +1,133 @@ +diff --git a/js/plugins/navigate/scroll.js b/js/plugins/navigate/scroll.js +index ecabbfab..5affa716 100644 +--- a/js/plugins/navigate/scroll.js ++++ b/js/plugins/navigate/scroll.js +@@ -26,9 +26,34 @@ export function restoreScrollPositionOrScrollToTop() { + + queueMicrotask(() => { + queueMicrotask(() => { // Double microtask here to make sure scrolling restoration is the LAST thing to happen. (Even after Alpine's x-init functions)... ++ let shouldScrollToFragment = ! document.body.hasAttribute('data-scroll-x') ++ + scroll(document.body) + + document.querySelectorAll(['[x-navigate\\:scroll]', '[wire\\:scroll]']).forEach(scroll) ++ ++ if (shouldScrollToFragment) { ++ getFragmentTarget()?.scrollIntoView({ behavior: 'instant' }) ++ } + }) + }) + } ++ ++function getFragmentTarget() { ++ let fragment = window.location.hash.substring(1) ++ ++ if (! fragment) return ++ ++ let target = document.getElementById(fragment) ++ ++ if (target) return target ++ ++ try { ++ fragment = decodeURIComponent(fragment) ++ } catch (e) { ++ // A malformed escape sequence can still be a valid element ID or name. ++ } ++ ++ return document.getElementById(fragment) ++ || Array.from(document.getElementsByName(fragment)).find(el => el.tagName === 'A') ++} +diff --git a/src/Features/SupportNavigate/BrowserTest.php b/src/Features/SupportNavigate/BrowserTest.php +index 1610f12d..725cb5fe 100644 +--- a/src/Features/SupportNavigate/BrowserTest.php ++++ b/src/Features/SupportNavigate/BrowserTest.php +@@ -646,6 +646,60 @@ class BrowserTest extends \Tests\BrowserTestCase + }); + } + ++ public function test_navigate_scrolls_to_fragment_targets() ++ { ++ $this->browse(function ($browser) { ++ foreach (['comments', 'comments%3Areplies', '100%', 'legacy-comments'] as $index => $fragment) { ++ $browser ++ ->visit('/first-scroll') ++ ->waitForNavigate()->click('@link.to.fragment.'.$index) ++ ->assertFragmentIs($fragment) ++ ->assertInViewPort('@second-target'); ++ } ++ }); ++ } ++ ++ public function test_navigate_with_an_unknown_fragment_scrolls_to_top() ++ { ++ $this->browse(function ($browser) { ++ $browser ++ ->visit('/first-scroll') ++ ->waitForNavigate()->click('@link.to.fragment.4') ++ ->assertFragmentIs('missing') ++ ->assertScript('window.scrollY', 0); ++ }); ++ } ++ ++ public function test_navigate_fragment_does_not_override_history_scroll_restoration() ++ { ++ $this->browse(function ($browser) { ++ $browser ++ ->visit('/first-scroll') ++ ->waitForNavigate()->click('@link.to.fragment.0') ++ ->assertInViewPort('@second-target'); ++ ++ $browser->script('window.scrollTo(0, 0)'); ++ ++ $browser ++ ->assertScript('window.scrollY', 0) ++ ->waitForNavigate()->back() ++ ->waitForNavigate()->forward() ++ ->assertFragmentIs('comments') ++ ->assertScript('window.scrollY', 0); ++ }); ++ } ++ ++ public function test_navigate_fragment_respects_preserve_scroll() ++ { ++ $this->browse(function ($browser) { ++ $browser ++ ->visit('/first-scroll') ++ ->waitForNavigate()->click('@link.to.fragment.with.preserve.scroll') ++ ->assertFragmentIs('comments') ++ ->assertScript('window.scrollY', 0); ++ }); ++ } ++ + public function test_navigate_scrolls_to_top_and_back_preserves_scroll() + { + $this->browse(function ($browser) { +@@ -1631,6 +1685,14 @@ class FirstScrollPage extends Component +
+
On first
+ ++
++ Preserve scroll ++ ++ @foreach (['comments', 'comments%3Areplies', '100%', 'legacy-comments', 'missing'] as $fragment) ++ Go to fragment ++ @endforeach ++
++ +
spacer
+ +
below the fold
+@@ -1696,7 +1758,12 @@ class SecondScrollPage extends Component + +
spacer
+ +-
below the fold
++
++ Replies ++ Percentage ++ Legacy comments ++ below the fold ++
+ +
spacer
+
diff --git a/tasks/livewire__livewire-10701/tests/test.sh b/tasks/livewire__livewire-10701/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..12e67e2ddfc098cd4b8e2b29908db8c670e182ce --- /dev/null +++ b/tasks/livewire__livewire-10701/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 6d0cdec2e34b060e56e7d6020dc47a9852320eb7 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/livewire__livewire-10701/tests/verifier.py b/tasks/livewire__livewire-10701/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/livewire__livewire-10701/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/livewire__livewire-10702/environment/Dockerfile b/tasks/livewire__livewire-10702/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..bab7966a6b28a0a9efba0e80d9eb28407157b5f7 --- /dev/null +++ b/tasks/livewire__livewire-10702/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/livewire/livewire.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/livewire/livewire.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/livewire/livewire.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 2b5961b257c4176a5ebc3cd7429d1e11abe8812e 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 2b5961b257c4176a5ebc3cd7429d1e11abe8812e \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 2b5961b257c4176a5ebc3cd7429d1e11abe8812e \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/livewire__livewire-10702/instruction.md b/tasks/livewire__livewire-10702/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..791599b62507f0bd3dd6e096974c2c2f9d3f1cff --- /dev/null +++ b/tasks/livewire__livewire-10702/instruction.md @@ -0,0 +1,19 @@ +# Issue + +**Title:** Require Alpine 3.17.3 on 4.x + +## Description + +Update 4.x to consume Alpine 3.17.3 from npm. + +This branch is rebased onto the current 4.x head and includes registry-generated package-lock.json integrity metadata for Alpine and all ten bundled plugins. + +Verification: +- Fresh npm install and npm ci passed. +- Production asset build passed. +- JavaScript suite passed: 110 tests, with 1 skipped. +- All 64 current GitHub checks passed across the original and ready-for-review matrices. Two isolated browser timing failures cleared on failed-job-only retry and required no product change. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `2b5961b257c4`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10702/solution/patch.diff b/tasks/livewire__livewire-10702/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..5190151677096e683aa933ee285cae91b157f811 --- /dev/null +++ b/tasks/livewire__livewire-10702/solution/patch.diff @@ -0,0 +1,185 @@ +diff --git a/package-lock.json b/package-lock.json +index 0788dec8..8b0e1f48 100644 +--- a/package-lock.json ++++ b/package-lock.json +@@ -7,18 +7,18 @@ + "name": "laravel-livewire", + "license": "MIT", + "dependencies": { +- "@alpinejs/anchor": "^3.17.2", +- "@alpinejs/collapse": "^3.17.2", +- "@alpinejs/csp": "^3.17.2", +- "@alpinejs/focus": "^3.17.2", +- "@alpinejs/intersect": "^3.17.2", +- "@alpinejs/mask": "^3.17.2", +- "@alpinejs/morph": "^3.17.2", +- "@alpinejs/persist": "^3.17.2", +- "@alpinejs/resize": "^3.17.2", +- "@alpinejs/sort": "^3.17.2", ++ "@alpinejs/anchor": "^3.17.3", ++ "@alpinejs/collapse": "^3.17.3", ++ "@alpinejs/csp": "^3.17.3", ++ "@alpinejs/focus": "^3.17.3", ++ "@alpinejs/intersect": "^3.17.3", ++ "@alpinejs/mask": "^3.17.3", ++ "@alpinejs/morph": "^3.17.3", ++ "@alpinejs/persist": "^3.17.3", ++ "@alpinejs/resize": "^3.17.3", ++ "@alpinejs/sort": "^3.17.3", + "@vue/reactivity": "^3.2.45", +- "alpinejs": "^3.17.2", ++ "alpinejs": "^3.17.3", + "nprogress": "^0.2.0" + }, + "devDependencies": { +@@ -29,33 +29,33 @@ + } + }, + "node_modules/@alpinejs/anchor": { +- "version": "3.17.2", +- "resolved": "https://registry.npmjs.org/@alpinejs/anchor/-/anchor-3.17.2.tgz", +- "integrity": "sha512-b4I/HwzG6o1L1hOcuGSxDuFUVJH4MgKWC+xr5fxWvUNeqqsTyB0ioqhfcqoA0vvIFnm9eLhGuwiKt4FymZis0A==", ++ "version": "3.17.3", ++ "resolved": "https://registry.npmjs.org/@alpinejs/anchor/-/anchor-3.17.3.tgz", ++ "integrity": "sha512-BeKw+NCjkni6pya8jMZpPeL429L+qoSHIUs15LCbPF03bsANyWjUIC2jZ85PX+y6X9hjI1k4GQUIHwI/yRtWXw==", + "license": "MIT", + "dependencies": { + "@floating-ui/dom": "^1.5.3" + } + }, + "node_modules/@alpinejs/collapse": { +- "version": "3.17.2", +- "resolved": "https://registry.npmjs.org/@alpinejs/collapse/-/collapse-3.17.2.tgz", +- "integrity": "sha512-OugjrAUGXkg8Msmitgf3rXFyoSYXchN00LPQYC2zDjaTcuRaVXXseBZcCU7DZ7b6cyZzCvYbIYngbaaEzvEfuw==", ++ "version": "3.17.3", ++ "resolved": "https://registry.npmjs.org/@alpinejs/collapse/-/collapse-3.17.3.tgz", ++ "integrity": "sha512-pAROM7iHkwDtKmqWrWFII5/cOD4M/oTi3UyS0b8mNOLjIsNZ1YO32K+6rpwpuBfRAZgNxU0K1UntuLR9+p9Log==", + "license": "MIT" + }, + "node_modules/@alpinejs/csp": { +- "version": "3.17.2", +- "resolved": "https://registry.npmjs.org/@alpinejs/csp/-/csp-3.17.2.tgz", +- "integrity": "sha512-jJXIzBaplTu1xVuhtNXEYDQDbQrdVJbXHYSVeF22fz4Vzm+g0X2XMb4pY1ywEpYLsFRx7ZcBE5gMyyuJpKPfHg==", ++ "version": "3.17.3", ++ "resolved": "https://registry.npmjs.org/@alpinejs/csp/-/csp-3.17.3.tgz", ++ "integrity": "sha512-Y24sCNahmtdfSp4awWBRmdqHfWrZPfuoa++0YqI6BuEaZ/Xjn8BOuBOScO+fzCXK0V2Vo9Ryy9tWQnTIVMyObQ==", + "license": "MIT", + "dependencies": { + "@vue/reactivity": "~3.5.40" + } + }, + "node_modules/@alpinejs/focus": { +- "version": "3.17.2", +- "resolved": "https://registry.npmjs.org/@alpinejs/focus/-/focus-3.17.2.tgz", +- "integrity": "sha512-ZYER+iuYu9IHT2ihAaP04alQLzLzH5nEMmFwVDe7Yu6bzeub+yJISYjR2hH+DlQTcmAZc7xnFMb6zscCVI091Q==", ++ "version": "3.17.3", ++ "resolved": "https://registry.npmjs.org/@alpinejs/focus/-/focus-3.17.3.tgz", ++ "integrity": "sha512-d91S3KiSnOyrMBfKsWoHKEw+ZPlVWHkaHBQgwPDOFgdVAxFsvZXEXi1EzX0QbOtLW9HqQwcFiqxoxRgs59UNyg==", + "license": "MIT", + "dependencies": { + "focus-trap": "^8.0.0", +@@ -63,39 +63,39 @@ + } + }, + "node_modules/@alpinejs/intersect": { +- "version": "3.17.2", +- "resolved": "https://registry.npmjs.org/@alpinejs/intersect/-/intersect-3.17.2.tgz", +- "integrity": "sha512-q4AJZDk7l/q7PaLeacMmdCfCCtgU3Qve9QTt4t6+A0z8F3YU2xqku08O9N7IENwiPKxlWseqXWWSlr97FSyZ9w==", ++ "version": "3.17.3", ++ "resolved": "https://registry.npmjs.org/@alpinejs/intersect/-/intersect-3.17.3.tgz", ++ "integrity": "sha512-uBlcZ5UnEPGVlGCdXHguPgwMiBZJqNA1vrIBvbP6qBjeYJx4nE4YlWQztXBTJgZbU5BtWKo9pGZbzvFOlX+T/Q==", + "license": "MIT" + }, + "node_modules/@alpinejs/mask": { +- "version": "3.17.2", +- "resolved": "https://registry.npmjs.org/@alpinejs/mask/-/mask-3.17.2.tgz", +- "integrity": "sha512-o2ht803nXshsYyNFvR4cUg/9XijF9eqwN8FFEVJUxriVJRS5jWDVADjijHcjQuVKGJYmzdnUMSLBPv48F8In9Q==", ++ "version": "3.17.3", ++ "resolved": "https://registry.npmjs.org/@alpinejs/mask/-/mask-3.17.3.tgz", ++ "integrity": "sha512-u8CD0FnmCApoqcZEr/6lOnrZzh4noVbiI+nEGIqhc9rj8ZA7rCt+Gtr6WDSsf5Dg1thTIfe5ykDg/WseiZl64g==", + "license": "MIT" + }, + "node_modules/@alpinejs/morph": { +- "version": "3.17.2", +- "resolved": "https://registry.npmjs.org/@alpinejs/morph/-/morph-3.17.2.tgz", +- "integrity": "sha512-9O+m1ChwU3JNFsTY7WDAOdG3qPYmE5zJp+2XWX/ymc57S9ifmmx0RCnRR/14CPEqTc/cdpUIOlnAGBg0NAGHpw==", ++ "version": "3.17.3", ++ "resolved": "https://registry.npmjs.org/@alpinejs/morph/-/morph-3.17.3.tgz", ++ "integrity": "sha512-1oW48NjXKjLLzg4o7avVbZMz/pd7/pvlVHNOtF15pxVf5VUUg8Jq5F0wN8+eSlmU+LxyF3XWOZDtOEwY8/O1Aw==", + "license": "MIT" + }, + "node_modules/@alpinejs/persist": { +- "version": "3.17.2", +- "resolved": "https://registry.npmjs.org/@alpinejs/persist/-/persist-3.17.2.tgz", +- "integrity": "sha512-BN8v27efELn2IgWjFoY0IkUmT1JOt3gUwEIb+2rjCU875E6VDbc6n0d29l9giITRgqyugm00H/xB1kcPVrQlcQ==", ++ "version": "3.17.3", ++ "resolved": "https://registry.npmjs.org/@alpinejs/persist/-/persist-3.17.3.tgz", ++ "integrity": "sha512-6Fm40qY3uIFoLEHd1jAolt3iUgdYGDqgW7N4W2hqBlJO4JMzMHAMzcN9weFBcMcwd9eQrO016Qvt3kryGu1abw==", + "license": "MIT" + }, + "node_modules/@alpinejs/resize": { +- "version": "3.17.2", +- "resolved": "https://registry.npmjs.org/@alpinejs/resize/-/resize-3.17.2.tgz", +- "integrity": "sha512-6v/LECG5pHMh/5iAY/PSPilZZtgt6kVmbpTTyLScmusIt1wyGqbX/wLXJnJwnr40Swb3B4ZImEBK9r1+GDlC8g==", ++ "version": "3.17.3", ++ "resolved": "https://registry.npmjs.org/@alpinejs/resize/-/resize-3.17.3.tgz", ++ "integrity": "sha512-7FKc7a/yFHhd9ikX02Fu35+y+f4IgbUfL3Sy77ufHjzbEU3TXmvHPPmfsbCyJZBMXtNJfVPrck1LkC/pspwO/g==", + "license": "MIT" + }, + "node_modules/@alpinejs/sort": { +- "version": "3.17.2", +- "resolved": "https://registry.npmjs.org/@alpinejs/sort/-/sort-3.17.2.tgz", +- "integrity": "sha512-72v63zuFkepgO2nwi8wNrD1z6pAY3S+d+lCwSZ9Q39hkIFISxPXKffEh3qtTu7Dzlc98EYLz4kVS/pxp3mdw5g==", ++ "version": "3.17.3", ++ "resolved": "https://registry.npmjs.org/@alpinejs/sort/-/sort-3.17.3.tgz", ++ "integrity": "sha512-Yq2PpXwnOrhb3wr+KkBbs/jB4WPFGm7S5O3i/okgeQjrw/q6KohP7Fdn5Q9Q9Az4DBeBc3EUg0161+g9KOr8Qg==", + "license": "MIT", + "dependencies": { + "sortablejs": "^1.15.2" +@@ -768,9 +768,9 @@ + } + }, + "node_modules/alpinejs": { +- "version": "3.17.2", +- "resolved": "https://registry.npmjs.org/alpinejs/-/alpinejs-3.17.2.tgz", +- "integrity": "sha512-xbnG3LlnmFkiNO49C+qhqjEDqOdB0snKqvT48ZVp8TakpZOpsoQbc/jAxpptQRjZi7c9rLeCfvwQ/XOSirIZFQ==", ++ "version": "3.17.3", ++ "resolved": "https://registry.npmjs.org/alpinejs/-/alpinejs-3.17.3.tgz", ++ "integrity": "sha512-hIfoRTBBeHMeMu6gXuKwwNoY6pJ7bwpZ91dXVrqRhUhHFOyGr4S21sUYqbxPY5Cnjo0RAmPZVRRZw1becRyV0Q==", + "license": "MIT", + "dependencies": { + "@vue/reactivity": "~3.5.40" +diff --git a/package.json b/package.json +index fd0c48b7..c26364e9 100644 +--- a/package.json ++++ b/package.json +@@ -17,18 +17,18 @@ + "vitest": "^4.1.11" + }, + "dependencies": { +- "@alpinejs/anchor": "^3.17.2", +- "@alpinejs/collapse": "^3.17.2", +- "@alpinejs/csp": "^3.17.2", +- "@alpinejs/focus": "^3.17.2", +- "@alpinejs/intersect": "^3.17.2", +- "@alpinejs/mask": "^3.17.2", +- "@alpinejs/morph": "^3.17.2", +- "@alpinejs/persist": "^3.17.2", +- "@alpinejs/resize": "^3.17.2", +- "@alpinejs/sort": "^3.17.2", ++ "@alpinejs/anchor": "^3.17.3", ++ "@alpinejs/collapse": "^3.17.3", ++ "@alpinejs/csp": "^3.17.3", ++ "@alpinejs/focus": "^3.17.3", ++ "@alpinejs/intersect": "^3.17.3", ++ "@alpinejs/mask": "^3.17.3", ++ "@alpinejs/morph": "^3.17.3", ++ "@alpinejs/persist": "^3.17.3", ++ "@alpinejs/resize": "^3.17.3", ++ "@alpinejs/sort": "^3.17.3", + "@vue/reactivity": "^3.2.45", +- "alpinejs": "^3.17.2", ++ "alpinejs": "^3.17.3", + "nprogress": "^0.2.0" + } + } diff --git a/tasks/livewire__livewire-10702/solution/solve.sh b/tasks/livewire__livewire-10702/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/livewire__livewire-10702/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/livewire__livewire-10702/task.toml b/tasks/livewire__livewire-10702/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..8c331d091bf6e7fd206f1e5b9953464025f28a04 --- /dev/null +++ b/tasks/livewire__livewire-10702/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/livewire__livewire-10702" +description = "Require Alpine 3.17.3 on 4.x" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "livewire", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "livewire/livewire" +ref = "2b5961b257c4176a5ebc3cd7429d1e11abe8812e" +reference = "https://github.com/livewire/livewire/pull/10702" +source_access = "auto" +built_at = "2026-11-16T16:09:51.485241+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:f2d040c223839e594be5a070fc273290016bffa189511dad9fb3eb92deb8aadc" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-14T19:00:51Z" +diff_format = "unified" +context_files = [ + "package-lock.json", + "package.json", +] +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.413907+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:e4107b76efa90bc7a1aaadc7cf2703949c6cb84569f39ef4a7a48597719edb92" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/livewire__livewire-10702/tests/capture.py b/tasks/livewire__livewire-10702/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/livewire__livewire-10702/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/livewire__livewire-10702/tests/instruction.md b/tasks/livewire__livewire-10702/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..791599b62507f0bd3dd6e096974c2c2f9d3f1cff --- /dev/null +++ b/tasks/livewire__livewire-10702/tests/instruction.md @@ -0,0 +1,19 @@ +# Issue + +**Title:** Require Alpine 3.17.3 on 4.x + +## Description + +Update 4.x to consume Alpine 3.17.3 from npm. + +This branch is rebased onto the current 4.x head and includes registry-generated package-lock.json integrity metadata for Alpine and all ten bundled plugins. + +Verification: +- Fresh npm install and npm ci passed. +- Production asset build passed. +- JavaScript suite passed: 110 tests, with 1 skipped. +- All 64 current GitHub checks passed across the original and ready-for-review matrices. Two isolated browser timing failures cleared on failed-job-only retry and required no product change. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `2b5961b257c4`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10702/tests/oracle.patch b/tasks/livewire__livewire-10702/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..5190151677096e683aa933ee285cae91b157f811 --- /dev/null +++ b/tasks/livewire__livewire-10702/tests/oracle.patch @@ -0,0 +1,185 @@ +diff --git a/package-lock.json b/package-lock.json +index 0788dec8..8b0e1f48 100644 +--- a/package-lock.json ++++ b/package-lock.json +@@ -7,18 +7,18 @@ + "name": "laravel-livewire", + "license": "MIT", + "dependencies": { +- "@alpinejs/anchor": "^3.17.2", +- "@alpinejs/collapse": "^3.17.2", +- "@alpinejs/csp": "^3.17.2", +- "@alpinejs/focus": "^3.17.2", +- "@alpinejs/intersect": "^3.17.2", +- "@alpinejs/mask": "^3.17.2", +- "@alpinejs/morph": "^3.17.2", +- "@alpinejs/persist": "^3.17.2", +- "@alpinejs/resize": "^3.17.2", +- "@alpinejs/sort": "^3.17.2", ++ "@alpinejs/anchor": "^3.17.3", ++ "@alpinejs/collapse": "^3.17.3", ++ "@alpinejs/csp": "^3.17.3", ++ "@alpinejs/focus": "^3.17.3", ++ "@alpinejs/intersect": "^3.17.3", ++ "@alpinejs/mask": "^3.17.3", ++ "@alpinejs/morph": "^3.17.3", ++ "@alpinejs/persist": "^3.17.3", ++ "@alpinejs/resize": "^3.17.3", ++ "@alpinejs/sort": "^3.17.3", + "@vue/reactivity": "^3.2.45", +- "alpinejs": "^3.17.2", ++ "alpinejs": "^3.17.3", + "nprogress": "^0.2.0" + }, + "devDependencies": { +@@ -29,33 +29,33 @@ + } + }, + "node_modules/@alpinejs/anchor": { +- "version": "3.17.2", +- "resolved": "https://registry.npmjs.org/@alpinejs/anchor/-/anchor-3.17.2.tgz", +- "integrity": "sha512-b4I/HwzG6o1L1hOcuGSxDuFUVJH4MgKWC+xr5fxWvUNeqqsTyB0ioqhfcqoA0vvIFnm9eLhGuwiKt4FymZis0A==", ++ "version": "3.17.3", ++ "resolved": "https://registry.npmjs.org/@alpinejs/anchor/-/anchor-3.17.3.tgz", ++ "integrity": "sha512-BeKw+NCjkni6pya8jMZpPeL429L+qoSHIUs15LCbPF03bsANyWjUIC2jZ85PX+y6X9hjI1k4GQUIHwI/yRtWXw==", + "license": "MIT", + "dependencies": { + "@floating-ui/dom": "^1.5.3" + } + }, + "node_modules/@alpinejs/collapse": { +- "version": "3.17.2", +- "resolved": "https://registry.npmjs.org/@alpinejs/collapse/-/collapse-3.17.2.tgz", +- "integrity": "sha512-OugjrAUGXkg8Msmitgf3rXFyoSYXchN00LPQYC2zDjaTcuRaVXXseBZcCU7DZ7b6cyZzCvYbIYngbaaEzvEfuw==", ++ "version": "3.17.3", ++ "resolved": "https://registry.npmjs.org/@alpinejs/collapse/-/collapse-3.17.3.tgz", ++ "integrity": "sha512-pAROM7iHkwDtKmqWrWFII5/cOD4M/oTi3UyS0b8mNOLjIsNZ1YO32K+6rpwpuBfRAZgNxU0K1UntuLR9+p9Log==", + "license": "MIT" + }, + "node_modules/@alpinejs/csp": { +- "version": "3.17.2", +- "resolved": "https://registry.npmjs.org/@alpinejs/csp/-/csp-3.17.2.tgz", +- "integrity": "sha512-jJXIzBaplTu1xVuhtNXEYDQDbQrdVJbXHYSVeF22fz4Vzm+g0X2XMb4pY1ywEpYLsFRx7ZcBE5gMyyuJpKPfHg==", ++ "version": "3.17.3", ++ "resolved": "https://registry.npmjs.org/@alpinejs/csp/-/csp-3.17.3.tgz", ++ "integrity": "sha512-Y24sCNahmtdfSp4awWBRmdqHfWrZPfuoa++0YqI6BuEaZ/Xjn8BOuBOScO+fzCXK0V2Vo9Ryy9tWQnTIVMyObQ==", + "license": "MIT", + "dependencies": { + "@vue/reactivity": "~3.5.40" + } + }, + "node_modules/@alpinejs/focus": { +- "version": "3.17.2", +- "resolved": "https://registry.npmjs.org/@alpinejs/focus/-/focus-3.17.2.tgz", +- "integrity": "sha512-ZYER+iuYu9IHT2ihAaP04alQLzLzH5nEMmFwVDe7Yu6bzeub+yJISYjR2hH+DlQTcmAZc7xnFMb6zscCVI091Q==", ++ "version": "3.17.3", ++ "resolved": "https://registry.npmjs.org/@alpinejs/focus/-/focus-3.17.3.tgz", ++ "integrity": "sha512-d91S3KiSnOyrMBfKsWoHKEw+ZPlVWHkaHBQgwPDOFgdVAxFsvZXEXi1EzX0QbOtLW9HqQwcFiqxoxRgs59UNyg==", + "license": "MIT", + "dependencies": { + "focus-trap": "^8.0.0", +@@ -63,39 +63,39 @@ + } + }, + "node_modules/@alpinejs/intersect": { +- "version": "3.17.2", +- "resolved": "https://registry.npmjs.org/@alpinejs/intersect/-/intersect-3.17.2.tgz", +- "integrity": "sha512-q4AJZDk7l/q7PaLeacMmdCfCCtgU3Qve9QTt4t6+A0z8F3YU2xqku08O9N7IENwiPKxlWseqXWWSlr97FSyZ9w==", ++ "version": "3.17.3", ++ "resolved": "https://registry.npmjs.org/@alpinejs/intersect/-/intersect-3.17.3.tgz", ++ "integrity": "sha512-uBlcZ5UnEPGVlGCdXHguPgwMiBZJqNA1vrIBvbP6qBjeYJx4nE4YlWQztXBTJgZbU5BtWKo9pGZbzvFOlX+T/Q==", + "license": "MIT" + }, + "node_modules/@alpinejs/mask": { +- "version": "3.17.2", +- "resolved": "https://registry.npmjs.org/@alpinejs/mask/-/mask-3.17.2.tgz", +- "integrity": "sha512-o2ht803nXshsYyNFvR4cUg/9XijF9eqwN8FFEVJUxriVJRS5jWDVADjijHcjQuVKGJYmzdnUMSLBPv48F8In9Q==", ++ "version": "3.17.3", ++ "resolved": "https://registry.npmjs.org/@alpinejs/mask/-/mask-3.17.3.tgz", ++ "integrity": "sha512-u8CD0FnmCApoqcZEr/6lOnrZzh4noVbiI+nEGIqhc9rj8ZA7rCt+Gtr6WDSsf5Dg1thTIfe5ykDg/WseiZl64g==", + "license": "MIT" + }, + "node_modules/@alpinejs/morph": { +- "version": "3.17.2", +- "resolved": "https://registry.npmjs.org/@alpinejs/morph/-/morph-3.17.2.tgz", +- "integrity": "sha512-9O+m1ChwU3JNFsTY7WDAOdG3qPYmE5zJp+2XWX/ymc57S9ifmmx0RCnRR/14CPEqTc/cdpUIOlnAGBg0NAGHpw==", ++ "version": "3.17.3", ++ "resolved": "https://registry.npmjs.org/@alpinejs/morph/-/morph-3.17.3.tgz", ++ "integrity": "sha512-1oW48NjXKjLLzg4o7avVbZMz/pd7/pvlVHNOtF15pxVf5VUUg8Jq5F0wN8+eSlmU+LxyF3XWOZDtOEwY8/O1Aw==", + "license": "MIT" + }, + "node_modules/@alpinejs/persist": { +- "version": "3.17.2", +- "resolved": "https://registry.npmjs.org/@alpinejs/persist/-/persist-3.17.2.tgz", +- "integrity": "sha512-BN8v27efELn2IgWjFoY0IkUmT1JOt3gUwEIb+2rjCU875E6VDbc6n0d29l9giITRgqyugm00H/xB1kcPVrQlcQ==", ++ "version": "3.17.3", ++ "resolved": "https://registry.npmjs.org/@alpinejs/persist/-/persist-3.17.3.tgz", ++ "integrity": "sha512-6Fm40qY3uIFoLEHd1jAolt3iUgdYGDqgW7N4W2hqBlJO4JMzMHAMzcN9weFBcMcwd9eQrO016Qvt3kryGu1abw==", + "license": "MIT" + }, + "node_modules/@alpinejs/resize": { +- "version": "3.17.2", +- "resolved": "https://registry.npmjs.org/@alpinejs/resize/-/resize-3.17.2.tgz", +- "integrity": "sha512-6v/LECG5pHMh/5iAY/PSPilZZtgt6kVmbpTTyLScmusIt1wyGqbX/wLXJnJwnr40Swb3B4ZImEBK9r1+GDlC8g==", ++ "version": "3.17.3", ++ "resolved": "https://registry.npmjs.org/@alpinejs/resize/-/resize-3.17.3.tgz", ++ "integrity": "sha512-7FKc7a/yFHhd9ikX02Fu35+y+f4IgbUfL3Sy77ufHjzbEU3TXmvHPPmfsbCyJZBMXtNJfVPrck1LkC/pspwO/g==", + "license": "MIT" + }, + "node_modules/@alpinejs/sort": { +- "version": "3.17.2", +- "resolved": "https://registry.npmjs.org/@alpinejs/sort/-/sort-3.17.2.tgz", +- "integrity": "sha512-72v63zuFkepgO2nwi8wNrD1z6pAY3S+d+lCwSZ9Q39hkIFISxPXKffEh3qtTu7Dzlc98EYLz4kVS/pxp3mdw5g==", ++ "version": "3.17.3", ++ "resolved": "https://registry.npmjs.org/@alpinejs/sort/-/sort-3.17.3.tgz", ++ "integrity": "sha512-Yq2PpXwnOrhb3wr+KkBbs/jB4WPFGm7S5O3i/okgeQjrw/q6KohP7Fdn5Q9Q9Az4DBeBc3EUg0161+g9KOr8Qg==", + "license": "MIT", + "dependencies": { + "sortablejs": "^1.15.2" +@@ -768,9 +768,9 @@ + } + }, + "node_modules/alpinejs": { +- "version": "3.17.2", +- "resolved": "https://registry.npmjs.org/alpinejs/-/alpinejs-3.17.2.tgz", +- "integrity": "sha512-xbnG3LlnmFkiNO49C+qhqjEDqOdB0snKqvT48ZVp8TakpZOpsoQbc/jAxpptQRjZi7c9rLeCfvwQ/XOSirIZFQ==", ++ "version": "3.17.3", ++ "resolved": "https://registry.npmjs.org/alpinejs/-/alpinejs-3.17.3.tgz", ++ "integrity": "sha512-hIfoRTBBeHMeMu6gXuKwwNoY6pJ7bwpZ91dXVrqRhUhHFOyGr4S21sUYqbxPY5Cnjo0RAmPZVRRZw1becRyV0Q==", + "license": "MIT", + "dependencies": { + "@vue/reactivity": "~3.5.40" +diff --git a/package.json b/package.json +index fd0c48b7..c26364e9 100644 +--- a/package.json ++++ b/package.json +@@ -17,18 +17,18 @@ + "vitest": "^4.1.11" + }, + "dependencies": { +- "@alpinejs/anchor": "^3.17.2", +- "@alpinejs/collapse": "^3.17.2", +- "@alpinejs/csp": "^3.17.2", +- "@alpinejs/focus": "^3.17.2", +- "@alpinejs/intersect": "^3.17.2", +- "@alpinejs/mask": "^3.17.2", +- "@alpinejs/morph": "^3.17.2", +- "@alpinejs/persist": "^3.17.2", +- "@alpinejs/resize": "^3.17.2", +- "@alpinejs/sort": "^3.17.2", ++ "@alpinejs/anchor": "^3.17.3", ++ "@alpinejs/collapse": "^3.17.3", ++ "@alpinejs/csp": "^3.17.3", ++ "@alpinejs/focus": "^3.17.3", ++ "@alpinejs/intersect": "^3.17.3", ++ "@alpinejs/mask": "^3.17.3", ++ "@alpinejs/morph": "^3.17.3", ++ "@alpinejs/persist": "^3.17.3", ++ "@alpinejs/resize": "^3.17.3", ++ "@alpinejs/sort": "^3.17.3", + "@vue/reactivity": "^3.2.45", +- "alpinejs": "^3.17.2", ++ "alpinejs": "^3.17.3", + "nprogress": "^0.2.0" + } + } diff --git a/tasks/livewire__livewire-10702/tests/test.sh b/tasks/livewire__livewire-10702/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..35e824e4ae06ef403606c655453bf1444a55bd46 --- /dev/null +++ b/tasks/livewire__livewire-10702/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 2b5961b257c4176a5ebc3cd7429d1e11abe8812e > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/livewire__livewire-10702/tests/verifier.py b/tasks/livewire__livewire-10702/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/livewire__livewire-10702/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/livewire__livewire-10703/environment/Dockerfile b/tasks/livewire__livewire-10703/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..fe2700c46e4883780799afbe9e7bb000de9cd2ca --- /dev/null +++ b/tasks/livewire__livewire-10703/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/livewire/livewire.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/livewire/livewire.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/livewire/livewire.git +WORKDIR /workspace +RUN git fetch --depth 1 origin ca22494bf4861fc30da2a2c08c74a5ecb2e88bff 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard ca22494bf4861fc30da2a2c08c74a5ecb2e88bff \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base ca22494bf4861fc30da2a2c08c74a5ecb2e88bff \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/livewire__livewire-10703/instruction.md b/tasks/livewire__livewire-10703/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f7f174e2af5653a5e0d982d9d08064d2fc576274 --- /dev/null +++ b/tasks/livewire__livewire-10703/instruction.md @@ -0,0 +1,19 @@ +# Issue + +**Title:** Require Alpine 3.17.3 on main + +## Description + +Update main to consume Alpine 3.17.3 from npm. + +This branch is rebased onto the current main head and includes registry-generated package-lock.json integrity metadata for Alpine and all ten bundled plugins. + +Verification: +- Fresh npm install and npm ci passed. +- Production asset build passed. +- JavaScript suite passed: 164 tests, with 1 skipped. +- All 64 current GitHub checks passed across the original and ready-for-review matrices. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `ca22494bf486`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10703/solution/patch.diff b/tasks/livewire__livewire-10703/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..04be75180d532105ceed67c182e7bdfdc6941b9b --- /dev/null +++ b/tasks/livewire__livewire-10703/solution/patch.diff @@ -0,0 +1,185 @@ +diff --git a/package-lock.json b/package-lock.json +index 2f324395..dd397950 100644 +--- a/package-lock.json ++++ b/package-lock.json +@@ -7,18 +7,18 @@ + "name": "laravel-livewire", + "license": "MIT", + "dependencies": { +- "@alpinejs/anchor": "^3.17.2", +- "@alpinejs/collapse": "^3.17.2", +- "@alpinejs/csp": "^3.17.2", +- "@alpinejs/focus": "^3.17.2", +- "@alpinejs/intersect": "^3.17.2", +- "@alpinejs/mask": "^3.17.2", +- "@alpinejs/morph": "^3.17.2", +- "@alpinejs/persist": "^3.17.2", +- "@alpinejs/resize": "^3.17.2", +- "@alpinejs/sort": "^3.17.2", ++ "@alpinejs/anchor": "^3.17.3", ++ "@alpinejs/collapse": "^3.17.3", ++ "@alpinejs/csp": "^3.17.3", ++ "@alpinejs/focus": "^3.17.3", ++ "@alpinejs/intersect": "^3.17.3", ++ "@alpinejs/mask": "^3.17.3", ++ "@alpinejs/morph": "^3.17.3", ++ "@alpinejs/persist": "^3.17.3", ++ "@alpinejs/resize": "^3.17.3", ++ "@alpinejs/sort": "^3.17.3", + "@vue/reactivity": "^3.2.45", +- "alpinejs": "^3.17.2", ++ "alpinejs": "^3.17.3", + "nprogress": "^0.2.0" + }, + "devDependencies": { +@@ -29,33 +29,33 @@ + } + }, + "node_modules/@alpinejs/anchor": { +- "version": "3.17.2", +- "resolved": "https://registry.npmjs.org/@alpinejs/anchor/-/anchor-3.17.2.tgz", +- "integrity": "sha512-b4I/HwzG6o1L1hOcuGSxDuFUVJH4MgKWC+xr5fxWvUNeqqsTyB0ioqhfcqoA0vvIFnm9eLhGuwiKt4FymZis0A==", ++ "version": "3.17.3", ++ "resolved": "https://registry.npmjs.org/@alpinejs/anchor/-/anchor-3.17.3.tgz", ++ "integrity": "sha512-BeKw+NCjkni6pya8jMZpPeL429L+qoSHIUs15LCbPF03bsANyWjUIC2jZ85PX+y6X9hjI1k4GQUIHwI/yRtWXw==", + "license": "MIT", + "dependencies": { + "@floating-ui/dom": "^1.5.3" + } + }, + "node_modules/@alpinejs/collapse": { +- "version": "3.17.2", +- "resolved": "https://registry.npmjs.org/@alpinejs/collapse/-/collapse-3.17.2.tgz", +- "integrity": "sha512-OugjrAUGXkg8Msmitgf3rXFyoSYXchN00LPQYC2zDjaTcuRaVXXseBZcCU7DZ7b6cyZzCvYbIYngbaaEzvEfuw==", ++ "version": "3.17.3", ++ "resolved": "https://registry.npmjs.org/@alpinejs/collapse/-/collapse-3.17.3.tgz", ++ "integrity": "sha512-pAROM7iHkwDtKmqWrWFII5/cOD4M/oTi3UyS0b8mNOLjIsNZ1YO32K+6rpwpuBfRAZgNxU0K1UntuLR9+p9Log==", + "license": "MIT" + }, + "node_modules/@alpinejs/csp": { +- "version": "3.17.2", +- "resolved": "https://registry.npmjs.org/@alpinejs/csp/-/csp-3.17.2.tgz", +- "integrity": "sha512-jJXIzBaplTu1xVuhtNXEYDQDbQrdVJbXHYSVeF22fz4Vzm+g0X2XMb4pY1ywEpYLsFRx7ZcBE5gMyyuJpKPfHg==", ++ "version": "3.17.3", ++ "resolved": "https://registry.npmjs.org/@alpinejs/csp/-/csp-3.17.3.tgz", ++ "integrity": "sha512-Y24sCNahmtdfSp4awWBRmdqHfWrZPfuoa++0YqI6BuEaZ/Xjn8BOuBOScO+fzCXK0V2Vo9Ryy9tWQnTIVMyObQ==", + "license": "MIT", + "dependencies": { + "@vue/reactivity": "~3.5.40" + } + }, + "node_modules/@alpinejs/focus": { +- "version": "3.17.2", +- "resolved": "https://registry.npmjs.org/@alpinejs/focus/-/focus-3.17.2.tgz", +- "integrity": "sha512-ZYER+iuYu9IHT2ihAaP04alQLzLzH5nEMmFwVDe7Yu6bzeub+yJISYjR2hH+DlQTcmAZc7xnFMb6zscCVI091Q==", ++ "version": "3.17.3", ++ "resolved": "https://registry.npmjs.org/@alpinejs/focus/-/focus-3.17.3.tgz", ++ "integrity": "sha512-d91S3KiSnOyrMBfKsWoHKEw+ZPlVWHkaHBQgwPDOFgdVAxFsvZXEXi1EzX0QbOtLW9HqQwcFiqxoxRgs59UNyg==", + "license": "MIT", + "dependencies": { + "focus-trap": "^8.0.0", +@@ -63,39 +63,39 @@ + } + }, + "node_modules/@alpinejs/intersect": { +- "version": "3.17.2", +- "resolved": "https://registry.npmjs.org/@alpinejs/intersect/-/intersect-3.17.2.tgz", +- "integrity": "sha512-q4AJZDk7l/q7PaLeacMmdCfCCtgU3Qve9QTt4t6+A0z8F3YU2xqku08O9N7IENwiPKxlWseqXWWSlr97FSyZ9w==", ++ "version": "3.17.3", ++ "resolved": "https://registry.npmjs.org/@alpinejs/intersect/-/intersect-3.17.3.tgz", ++ "integrity": "sha512-uBlcZ5UnEPGVlGCdXHguPgwMiBZJqNA1vrIBvbP6qBjeYJx4nE4YlWQztXBTJgZbU5BtWKo9pGZbzvFOlX+T/Q==", + "license": "MIT" + }, + "node_modules/@alpinejs/mask": { +- "version": "3.17.2", +- "resolved": "https://registry.npmjs.org/@alpinejs/mask/-/mask-3.17.2.tgz", +- "integrity": "sha512-o2ht803nXshsYyNFvR4cUg/9XijF9eqwN8FFEVJUxriVJRS5jWDVADjijHcjQuVKGJYmzdnUMSLBPv48F8In9Q==", ++ "version": "3.17.3", ++ "resolved": "https://registry.npmjs.org/@alpinejs/mask/-/mask-3.17.3.tgz", ++ "integrity": "sha512-u8CD0FnmCApoqcZEr/6lOnrZzh4noVbiI+nEGIqhc9rj8ZA7rCt+Gtr6WDSsf5Dg1thTIfe5ykDg/WseiZl64g==", + "license": "MIT" + }, + "node_modules/@alpinejs/morph": { +- "version": "3.17.2", +- "resolved": "https://registry.npmjs.org/@alpinejs/morph/-/morph-3.17.2.tgz", +- "integrity": "sha512-9O+m1ChwU3JNFsTY7WDAOdG3qPYmE5zJp+2XWX/ymc57S9ifmmx0RCnRR/14CPEqTc/cdpUIOlnAGBg0NAGHpw==", ++ "version": "3.17.3", ++ "resolved": "https://registry.npmjs.org/@alpinejs/morph/-/morph-3.17.3.tgz", ++ "integrity": "sha512-1oW48NjXKjLLzg4o7avVbZMz/pd7/pvlVHNOtF15pxVf5VUUg8Jq5F0wN8+eSlmU+LxyF3XWOZDtOEwY8/O1Aw==", + "license": "MIT" + }, + "node_modules/@alpinejs/persist": { +- "version": "3.17.2", +- "resolved": "https://registry.npmjs.org/@alpinejs/persist/-/persist-3.17.2.tgz", +- "integrity": "sha512-BN8v27efELn2IgWjFoY0IkUmT1JOt3gUwEIb+2rjCU875E6VDbc6n0d29l9giITRgqyugm00H/xB1kcPVrQlcQ==", ++ "version": "3.17.3", ++ "resolved": "https://registry.npmjs.org/@alpinejs/persist/-/persist-3.17.3.tgz", ++ "integrity": "sha512-6Fm40qY3uIFoLEHd1jAolt3iUgdYGDqgW7N4W2hqBlJO4JMzMHAMzcN9weFBcMcwd9eQrO016Qvt3kryGu1abw==", + "license": "MIT" + }, + "node_modules/@alpinejs/resize": { +- "version": "3.17.2", +- "resolved": "https://registry.npmjs.org/@alpinejs/resize/-/resize-3.17.2.tgz", +- "integrity": "sha512-6v/LECG5pHMh/5iAY/PSPilZZtgt6kVmbpTTyLScmusIt1wyGqbX/wLXJnJwnr40Swb3B4ZImEBK9r1+GDlC8g==", ++ "version": "3.17.3", ++ "resolved": "https://registry.npmjs.org/@alpinejs/resize/-/resize-3.17.3.tgz", ++ "integrity": "sha512-7FKc7a/yFHhd9ikX02Fu35+y+f4IgbUfL3Sy77ufHjzbEU3TXmvHPPmfsbCyJZBMXtNJfVPrck1LkC/pspwO/g==", + "license": "MIT" + }, + "node_modules/@alpinejs/sort": { +- "version": "3.17.2", +- "resolved": "https://registry.npmjs.org/@alpinejs/sort/-/sort-3.17.2.tgz", +- "integrity": "sha512-72v63zuFkepgO2nwi8wNrD1z6pAY3S+d+lCwSZ9Q39hkIFISxPXKffEh3qtTu7Dzlc98EYLz4kVS/pxp3mdw5g==", ++ "version": "3.17.3", ++ "resolved": "https://registry.npmjs.org/@alpinejs/sort/-/sort-3.17.3.tgz", ++ "integrity": "sha512-Yq2PpXwnOrhb3wr+KkBbs/jB4WPFGm7S5O3i/okgeQjrw/q6KohP7Fdn5Q9Q9Az4DBeBc3EUg0161+g9KOr8Qg==", + "license": "MIT", + "dependencies": { + "sortablejs": "^1.15.2" +@@ -1266,9 +1266,9 @@ + } + }, + "node_modules/alpinejs": { +- "version": "3.17.2", +- "resolved": "https://registry.npmjs.org/alpinejs/-/alpinejs-3.17.2.tgz", +- "integrity": "sha512-xbnG3LlnmFkiNO49C+qhqjEDqOdB0snKqvT48ZVp8TakpZOpsoQbc/jAxpptQRjZi7c9rLeCfvwQ/XOSirIZFQ==", ++ "version": "3.17.3", ++ "resolved": "https://registry.npmjs.org/alpinejs/-/alpinejs-3.17.3.tgz", ++ "integrity": "sha512-hIfoRTBBeHMeMu6gXuKwwNoY6pJ7bwpZ91dXVrqRhUhHFOyGr4S21sUYqbxPY5Cnjo0RAmPZVRRZw1becRyV0Q==", + "license": "MIT", + "dependencies": { + "@vue/reactivity": "~3.5.40" +diff --git a/package.json b/package.json +index 89ae6989..cb068fe1 100644 +--- a/package.json ++++ b/package.json +@@ -17,18 +17,18 @@ + "vitest": "^3.2.4" + }, + "dependencies": { +- "@alpinejs/anchor": "^3.17.2", +- "@alpinejs/collapse": "^3.17.2", +- "@alpinejs/csp": "^3.17.2", +- "@alpinejs/focus": "^3.17.2", +- "@alpinejs/intersect": "^3.17.2", +- "@alpinejs/mask": "^3.17.2", +- "@alpinejs/morph": "^3.17.2", +- "@alpinejs/persist": "^3.17.2", +- "@alpinejs/resize": "^3.17.2", +- "@alpinejs/sort": "^3.17.2", ++ "@alpinejs/anchor": "^3.17.3", ++ "@alpinejs/collapse": "^3.17.3", ++ "@alpinejs/csp": "^3.17.3", ++ "@alpinejs/focus": "^3.17.3", ++ "@alpinejs/intersect": "^3.17.3", ++ "@alpinejs/mask": "^3.17.3", ++ "@alpinejs/morph": "^3.17.3", ++ "@alpinejs/persist": "^3.17.3", ++ "@alpinejs/resize": "^3.17.3", ++ "@alpinejs/sort": "^3.17.3", + "@vue/reactivity": "^3.2.45", +- "alpinejs": "^3.17.2", ++ "alpinejs": "^3.17.3", + "nprogress": "^0.2.0" + } + } diff --git a/tasks/livewire__livewire-10703/solution/solve.sh b/tasks/livewire__livewire-10703/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/livewire__livewire-10703/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/livewire__livewire-10703/task.toml b/tasks/livewire__livewire-10703/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7ae99c99b555d3a216780c36f2912f883180838d --- /dev/null +++ b/tasks/livewire__livewire-10703/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/livewire__livewire-10703" +description = "Require Alpine 3.17.3 on main" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "livewire", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "livewire/livewire" +ref = "ca22494bf4861fc30da2a2c08c74a5ecb2e88bff" +reference = "https://github.com/livewire/livewire/pull/10703" +source_access = "auto" +built_at = "2026-11-16T16:09:51.483620+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:d9e562614e69079084eacfe3f992ba11d98e1e7dcae4ba6c152e0805ddfbf93e" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-14T19:01:08Z" +diff_format = "unified" +context_files = [ + "package-lock.json", + "package.json", +] +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.414368+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:3acb173630ac188490437ddf5494052b4c5205ca54e5b1d2f6118c276b19f51b" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/livewire__livewire-10703/tests/capture.py b/tasks/livewire__livewire-10703/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/livewire__livewire-10703/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/livewire__livewire-10703/tests/instruction.md b/tasks/livewire__livewire-10703/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f7f174e2af5653a5e0d982d9d08064d2fc576274 --- /dev/null +++ b/tasks/livewire__livewire-10703/tests/instruction.md @@ -0,0 +1,19 @@ +# Issue + +**Title:** Require Alpine 3.17.3 on main + +## Description + +Update main to consume Alpine 3.17.3 from npm. + +This branch is rebased onto the current main head and includes registry-generated package-lock.json integrity metadata for Alpine and all ten bundled plugins. + +Verification: +- Fresh npm install and npm ci passed. +- Production asset build passed. +- JavaScript suite passed: 164 tests, with 1 skipped. +- All 64 current GitHub checks passed across the original and ready-for-review matrices. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `ca22494bf486`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10703/tests/oracle.patch b/tasks/livewire__livewire-10703/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..04be75180d532105ceed67c182e7bdfdc6941b9b --- /dev/null +++ b/tasks/livewire__livewire-10703/tests/oracle.patch @@ -0,0 +1,185 @@ +diff --git a/package-lock.json b/package-lock.json +index 2f324395..dd397950 100644 +--- a/package-lock.json ++++ b/package-lock.json +@@ -7,18 +7,18 @@ + "name": "laravel-livewire", + "license": "MIT", + "dependencies": { +- "@alpinejs/anchor": "^3.17.2", +- "@alpinejs/collapse": "^3.17.2", +- "@alpinejs/csp": "^3.17.2", +- "@alpinejs/focus": "^3.17.2", +- "@alpinejs/intersect": "^3.17.2", +- "@alpinejs/mask": "^3.17.2", +- "@alpinejs/morph": "^3.17.2", +- "@alpinejs/persist": "^3.17.2", +- "@alpinejs/resize": "^3.17.2", +- "@alpinejs/sort": "^3.17.2", ++ "@alpinejs/anchor": "^3.17.3", ++ "@alpinejs/collapse": "^3.17.3", ++ "@alpinejs/csp": "^3.17.3", ++ "@alpinejs/focus": "^3.17.3", ++ "@alpinejs/intersect": "^3.17.3", ++ "@alpinejs/mask": "^3.17.3", ++ "@alpinejs/morph": "^3.17.3", ++ "@alpinejs/persist": "^3.17.3", ++ "@alpinejs/resize": "^3.17.3", ++ "@alpinejs/sort": "^3.17.3", + "@vue/reactivity": "^3.2.45", +- "alpinejs": "^3.17.2", ++ "alpinejs": "^3.17.3", + "nprogress": "^0.2.0" + }, + "devDependencies": { +@@ -29,33 +29,33 @@ + } + }, + "node_modules/@alpinejs/anchor": { +- "version": "3.17.2", +- "resolved": "https://registry.npmjs.org/@alpinejs/anchor/-/anchor-3.17.2.tgz", +- "integrity": "sha512-b4I/HwzG6o1L1hOcuGSxDuFUVJH4MgKWC+xr5fxWvUNeqqsTyB0ioqhfcqoA0vvIFnm9eLhGuwiKt4FymZis0A==", ++ "version": "3.17.3", ++ "resolved": "https://registry.npmjs.org/@alpinejs/anchor/-/anchor-3.17.3.tgz", ++ "integrity": "sha512-BeKw+NCjkni6pya8jMZpPeL429L+qoSHIUs15LCbPF03bsANyWjUIC2jZ85PX+y6X9hjI1k4GQUIHwI/yRtWXw==", + "license": "MIT", + "dependencies": { + "@floating-ui/dom": "^1.5.3" + } + }, + "node_modules/@alpinejs/collapse": { +- "version": "3.17.2", +- "resolved": "https://registry.npmjs.org/@alpinejs/collapse/-/collapse-3.17.2.tgz", +- "integrity": "sha512-OugjrAUGXkg8Msmitgf3rXFyoSYXchN00LPQYC2zDjaTcuRaVXXseBZcCU7DZ7b6cyZzCvYbIYngbaaEzvEfuw==", ++ "version": "3.17.3", ++ "resolved": "https://registry.npmjs.org/@alpinejs/collapse/-/collapse-3.17.3.tgz", ++ "integrity": "sha512-pAROM7iHkwDtKmqWrWFII5/cOD4M/oTi3UyS0b8mNOLjIsNZ1YO32K+6rpwpuBfRAZgNxU0K1UntuLR9+p9Log==", + "license": "MIT" + }, + "node_modules/@alpinejs/csp": { +- "version": "3.17.2", +- "resolved": "https://registry.npmjs.org/@alpinejs/csp/-/csp-3.17.2.tgz", +- "integrity": "sha512-jJXIzBaplTu1xVuhtNXEYDQDbQrdVJbXHYSVeF22fz4Vzm+g0X2XMb4pY1ywEpYLsFRx7ZcBE5gMyyuJpKPfHg==", ++ "version": "3.17.3", ++ "resolved": "https://registry.npmjs.org/@alpinejs/csp/-/csp-3.17.3.tgz", ++ "integrity": "sha512-Y24sCNahmtdfSp4awWBRmdqHfWrZPfuoa++0YqI6BuEaZ/Xjn8BOuBOScO+fzCXK0V2Vo9Ryy9tWQnTIVMyObQ==", + "license": "MIT", + "dependencies": { + "@vue/reactivity": "~3.5.40" + } + }, + "node_modules/@alpinejs/focus": { +- "version": "3.17.2", +- "resolved": "https://registry.npmjs.org/@alpinejs/focus/-/focus-3.17.2.tgz", +- "integrity": "sha512-ZYER+iuYu9IHT2ihAaP04alQLzLzH5nEMmFwVDe7Yu6bzeub+yJISYjR2hH+DlQTcmAZc7xnFMb6zscCVI091Q==", ++ "version": "3.17.3", ++ "resolved": "https://registry.npmjs.org/@alpinejs/focus/-/focus-3.17.3.tgz", ++ "integrity": "sha512-d91S3KiSnOyrMBfKsWoHKEw+ZPlVWHkaHBQgwPDOFgdVAxFsvZXEXi1EzX0QbOtLW9HqQwcFiqxoxRgs59UNyg==", + "license": "MIT", + "dependencies": { + "focus-trap": "^8.0.0", +@@ -63,39 +63,39 @@ + } + }, + "node_modules/@alpinejs/intersect": { +- "version": "3.17.2", +- "resolved": "https://registry.npmjs.org/@alpinejs/intersect/-/intersect-3.17.2.tgz", +- "integrity": "sha512-q4AJZDk7l/q7PaLeacMmdCfCCtgU3Qve9QTt4t6+A0z8F3YU2xqku08O9N7IENwiPKxlWseqXWWSlr97FSyZ9w==", ++ "version": "3.17.3", ++ "resolved": "https://registry.npmjs.org/@alpinejs/intersect/-/intersect-3.17.3.tgz", ++ "integrity": "sha512-uBlcZ5UnEPGVlGCdXHguPgwMiBZJqNA1vrIBvbP6qBjeYJx4nE4YlWQztXBTJgZbU5BtWKo9pGZbzvFOlX+T/Q==", + "license": "MIT" + }, + "node_modules/@alpinejs/mask": { +- "version": "3.17.2", +- "resolved": "https://registry.npmjs.org/@alpinejs/mask/-/mask-3.17.2.tgz", +- "integrity": "sha512-o2ht803nXshsYyNFvR4cUg/9XijF9eqwN8FFEVJUxriVJRS5jWDVADjijHcjQuVKGJYmzdnUMSLBPv48F8In9Q==", ++ "version": "3.17.3", ++ "resolved": "https://registry.npmjs.org/@alpinejs/mask/-/mask-3.17.3.tgz", ++ "integrity": "sha512-u8CD0FnmCApoqcZEr/6lOnrZzh4noVbiI+nEGIqhc9rj8ZA7rCt+Gtr6WDSsf5Dg1thTIfe5ykDg/WseiZl64g==", + "license": "MIT" + }, + "node_modules/@alpinejs/morph": { +- "version": "3.17.2", +- "resolved": "https://registry.npmjs.org/@alpinejs/morph/-/morph-3.17.2.tgz", +- "integrity": "sha512-9O+m1ChwU3JNFsTY7WDAOdG3qPYmE5zJp+2XWX/ymc57S9ifmmx0RCnRR/14CPEqTc/cdpUIOlnAGBg0NAGHpw==", ++ "version": "3.17.3", ++ "resolved": "https://registry.npmjs.org/@alpinejs/morph/-/morph-3.17.3.tgz", ++ "integrity": "sha512-1oW48NjXKjLLzg4o7avVbZMz/pd7/pvlVHNOtF15pxVf5VUUg8Jq5F0wN8+eSlmU+LxyF3XWOZDtOEwY8/O1Aw==", + "license": "MIT" + }, + "node_modules/@alpinejs/persist": { +- "version": "3.17.2", +- "resolved": "https://registry.npmjs.org/@alpinejs/persist/-/persist-3.17.2.tgz", +- "integrity": "sha512-BN8v27efELn2IgWjFoY0IkUmT1JOt3gUwEIb+2rjCU875E6VDbc6n0d29l9giITRgqyugm00H/xB1kcPVrQlcQ==", ++ "version": "3.17.3", ++ "resolved": "https://registry.npmjs.org/@alpinejs/persist/-/persist-3.17.3.tgz", ++ "integrity": "sha512-6Fm40qY3uIFoLEHd1jAolt3iUgdYGDqgW7N4W2hqBlJO4JMzMHAMzcN9weFBcMcwd9eQrO016Qvt3kryGu1abw==", + "license": "MIT" + }, + "node_modules/@alpinejs/resize": { +- "version": "3.17.2", +- "resolved": "https://registry.npmjs.org/@alpinejs/resize/-/resize-3.17.2.tgz", +- "integrity": "sha512-6v/LECG5pHMh/5iAY/PSPilZZtgt6kVmbpTTyLScmusIt1wyGqbX/wLXJnJwnr40Swb3B4ZImEBK9r1+GDlC8g==", ++ "version": "3.17.3", ++ "resolved": "https://registry.npmjs.org/@alpinejs/resize/-/resize-3.17.3.tgz", ++ "integrity": "sha512-7FKc7a/yFHhd9ikX02Fu35+y+f4IgbUfL3Sy77ufHjzbEU3TXmvHPPmfsbCyJZBMXtNJfVPrck1LkC/pspwO/g==", + "license": "MIT" + }, + "node_modules/@alpinejs/sort": { +- "version": "3.17.2", +- "resolved": "https://registry.npmjs.org/@alpinejs/sort/-/sort-3.17.2.tgz", +- "integrity": "sha512-72v63zuFkepgO2nwi8wNrD1z6pAY3S+d+lCwSZ9Q39hkIFISxPXKffEh3qtTu7Dzlc98EYLz4kVS/pxp3mdw5g==", ++ "version": "3.17.3", ++ "resolved": "https://registry.npmjs.org/@alpinejs/sort/-/sort-3.17.3.tgz", ++ "integrity": "sha512-Yq2PpXwnOrhb3wr+KkBbs/jB4WPFGm7S5O3i/okgeQjrw/q6KohP7Fdn5Q9Q9Az4DBeBc3EUg0161+g9KOr8Qg==", + "license": "MIT", + "dependencies": { + "sortablejs": "^1.15.2" +@@ -1266,9 +1266,9 @@ + } + }, + "node_modules/alpinejs": { +- "version": "3.17.2", +- "resolved": "https://registry.npmjs.org/alpinejs/-/alpinejs-3.17.2.tgz", +- "integrity": "sha512-xbnG3LlnmFkiNO49C+qhqjEDqOdB0snKqvT48ZVp8TakpZOpsoQbc/jAxpptQRjZi7c9rLeCfvwQ/XOSirIZFQ==", ++ "version": "3.17.3", ++ "resolved": "https://registry.npmjs.org/alpinejs/-/alpinejs-3.17.3.tgz", ++ "integrity": "sha512-hIfoRTBBeHMeMu6gXuKwwNoY6pJ7bwpZ91dXVrqRhUhHFOyGr4S21sUYqbxPY5Cnjo0RAmPZVRRZw1becRyV0Q==", + "license": "MIT", + "dependencies": { + "@vue/reactivity": "~3.5.40" +diff --git a/package.json b/package.json +index 89ae6989..cb068fe1 100644 +--- a/package.json ++++ b/package.json +@@ -17,18 +17,18 @@ + "vitest": "^3.2.4" + }, + "dependencies": { +- "@alpinejs/anchor": "^3.17.2", +- "@alpinejs/collapse": "^3.17.2", +- "@alpinejs/csp": "^3.17.2", +- "@alpinejs/focus": "^3.17.2", +- "@alpinejs/intersect": "^3.17.2", +- "@alpinejs/mask": "^3.17.2", +- "@alpinejs/morph": "^3.17.2", +- "@alpinejs/persist": "^3.17.2", +- "@alpinejs/resize": "^3.17.2", +- "@alpinejs/sort": "^3.17.2", ++ "@alpinejs/anchor": "^3.17.3", ++ "@alpinejs/collapse": "^3.17.3", ++ "@alpinejs/csp": "^3.17.3", ++ "@alpinejs/focus": "^3.17.3", ++ "@alpinejs/intersect": "^3.17.3", ++ "@alpinejs/mask": "^3.17.3", ++ "@alpinejs/morph": "^3.17.3", ++ "@alpinejs/persist": "^3.17.3", ++ "@alpinejs/resize": "^3.17.3", ++ "@alpinejs/sort": "^3.17.3", + "@vue/reactivity": "^3.2.45", +- "alpinejs": "^3.17.2", ++ "alpinejs": "^3.17.3", + "nprogress": "^0.2.0" + } + } diff --git a/tasks/livewire__livewire-10703/tests/test.sh b/tasks/livewire__livewire-10703/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..512eb24f98ac4a9ae133703ec4c863336f0a53e1 --- /dev/null +++ b/tasks/livewire__livewire-10703/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace ca22494bf4861fc30da2a2c08c74a5ecb2e88bff > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/livewire__livewire-10703/tests/verifier.py b/tasks/livewire__livewire-10703/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/livewire__livewire-10703/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/livewire__livewire-10704/environment/Dockerfile b/tasks/livewire__livewire-10704/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ca53211474ea663e507d1f3fa0c2de0c24d5893c --- /dev/null +++ b/tasks/livewire__livewire-10704/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/livewire/livewire.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/livewire/livewire.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/livewire/livewire.git +WORKDIR /workspace +RUN git fetch --depth 1 origin b300bbef93209b202f268525c46b30887204e8f2 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard b300bbef93209b202f268525c46b30887204e8f2 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base b300bbef93209b202f268525c46b30887204e8f2 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/livewire__livewire-10704/instruction.md b/tasks/livewire__livewire-10704/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e08952fc762687917b1140ed8b1c6f007e44e34d --- /dev/null +++ b/tasks/livewire__livewire-10704/instruction.md @@ -0,0 +1,18 @@ +# Issue + +**Title:** [4.x] Support direct assignment to virtual properties + +## Description + +Right now if you assign to a virtual property directly inside an action like `$this->selected = new Selection(...)` or `$this->items = collect(['a'])`, it creates a dynamic property on the component instead of updating the virtual property. + +Because `Component` has `__get()` and `__unset()` for virtual properties but no `__set()`, a few things break: +1. The assignment bypasses `setVirtualProperty()` and its `TypeError` check. +2. It assigns to a dynamic property which triggers a deprecation notice on PHP 8.2+. +3. During dehydration `InteractsWithProperties::all()` reads `$this->getVirtualProperties()`, which still has the old value from `$this->__virtualProperties` and overwrites the dynamic property, so the assignment is silently lost on the next request. + +This adds `__set()` to `Component.php` to route direct assignments through `setVirtualProperty()`, matching `__get()` and `__unset()`. Added tests covering roundtrip persistence, type errors on invalid assignment, and `data_set()`. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `b300bbef9320`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10704/solution/patch.diff b/tasks/livewire__livewire-10704/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..e5814ecfdd5170b132bcb691f2a1fa3dac94dd7e --- /dev/null +++ b/tasks/livewire__livewire-10704/solution/patch.diff @@ -0,0 +1,113 @@ +diff --git a/src/Component.php b/src/Component.php +index e6dd5427..9656679a 100644 +--- a/src/Component.php ++++ b/src/Component.php +@@ -136,6 +136,19 @@ abstract class Component + return $value; + } + ++ function __set($property, $value) ++ { ++ trigger('__set', $this, $property, $value); ++ ++ if ($this->hasVirtualProperty($property)) { ++ $this->setVirtualProperty($property, $value); ++ ++ return; ++ } ++ ++ $this->{$property} = $value; ++ } ++ + function __unset($property) + { + trigger('__unset', $this, $property); +diff --git a/src/Features/SupportVirtualProperties/UnitTest.php b/src/Features/SupportVirtualProperties/UnitTest.php +index b5749458..54ba40a1 100644 +--- a/src/Features/SupportVirtualProperties/UnitTest.php ++++ b/src/Features/SupportVirtualProperties/UnitTest.php +@@ -418,4 +418,84 @@ class UnitTest extends \Tests\TestCase + Assert::assertInstanceOf(Selection::class, $component->get('selected')); + Assert::assertSame([], $component->get('selected')->keys()); + } ++ ++ function test_a_virtual_property_can_be_assigned_directly_in_an_action() ++ { ++ $test = Livewire::test(new class extends TestComponent { ++ #[Virtual] ++ public function items(): Collection ++ { ++ return collect(['a', 'b']); ++ } ++ ++ public function replace() ++ { ++ $this->items = collect(['c', 'd']); ++ } ++ }); ++ ++ $test->call('replace'); ++ $test->call('$refresh'); ++ $test->assertSet('items', fn ($items) => $items->all() === ['c', 'd']); ++ } ++ ++ function test_assigning_an_invalid_type_to_a_virtual_property_directly_throws() ++ { ++ $this->expectException(\TypeError::class); ++ ++ $test = Livewire::test(new class extends TestComponent { ++ #[Virtual] ++ public function items(): Collection ++ { ++ return collect(['a', 'b']); ++ } ++ ++ public function invalid() ++ { ++ $this->items = 'not-a-collection'; ++ } ++ }); ++ ++ $test->call('invalid'); ++ } ++ ++ function test_a_virtual_property_can_be_assigned_using_data_set() ++ { ++ $test = Livewire::test(new class extends TestComponent { ++ #[Virtual] ++ public function items(): Collection ++ { ++ return collect(['a', 'b']); ++ } ++ ++ public function replace() ++ { ++ data_set($this, 'items', collect(['e', 'f'])); ++ } ++ }); ++ ++ $test->call('replace'); ++ $test->call('$refresh'); ++ $test->assertSet('items', fn ($items) => $items->all() === ['e', 'f']); ++ } ++ ++ function test_a_snake_case_virtual_property_can_be_assigned_directly() ++ { ++ $test = Livewire::test(new class extends TestComponent { ++ #[Virtual] ++ public function selectedItems(): Collection ++ { ++ return collect(['a']); ++ } ++ ++ public function replace() ++ { ++ $this->selected_items = collect(['b']); ++ } ++ }); ++ ++ $test->call('replace'); ++ $test->call('$refresh'); ++ $test->assertSet('selectedItems', fn ($items) => $items->all() === ['b']); ++ } + } diff --git a/tasks/livewire__livewire-10704/solution/solve.sh b/tasks/livewire__livewire-10704/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/livewire__livewire-10704/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/livewire__livewire-10704/task.toml b/tasks/livewire__livewire-10704/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..368bf9aae58fe93cebcfc017e4f65124a33442fd --- /dev/null +++ b/tasks/livewire__livewire-10704/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/livewire__livewire-10704" +description = "[4.x] Support direct assignment to virtual properties" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "livewire", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "livewire/livewire" +ref = "b300bbef93209b202f268525c46b30887204e8f2" +reference = "https://github.com/livewire/livewire/pull/10704" +source_access = "auto" +built_at = "2026-11-16T16:09:51.477251+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:093a6092e918697066be5b3989b09b82e20460164815560bd56e57798672b553" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-15T11:54:11Z" +diff_format = "unified" +context_files = [ + "src/Component.php", + "src/Features/SupportVirtualProperties/UnitTest.php", +] +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.414823+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:58954fa3376cafef3c407a47c3d44f8fa0da8fcaed48a553202b03397afe8b4b" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/livewire__livewire-10704/tests/capture.py b/tasks/livewire__livewire-10704/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/livewire__livewire-10704/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/livewire__livewire-10704/tests/instruction.md b/tasks/livewire__livewire-10704/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e08952fc762687917b1140ed8b1c6f007e44e34d --- /dev/null +++ b/tasks/livewire__livewire-10704/tests/instruction.md @@ -0,0 +1,18 @@ +# Issue + +**Title:** [4.x] Support direct assignment to virtual properties + +## Description + +Right now if you assign to a virtual property directly inside an action like `$this->selected = new Selection(...)` or `$this->items = collect(['a'])`, it creates a dynamic property on the component instead of updating the virtual property. + +Because `Component` has `__get()` and `__unset()` for virtual properties but no `__set()`, a few things break: +1. The assignment bypasses `setVirtualProperty()` and its `TypeError` check. +2. It assigns to a dynamic property which triggers a deprecation notice on PHP 8.2+. +3. During dehydration `InteractsWithProperties::all()` reads `$this->getVirtualProperties()`, which still has the old value from `$this->__virtualProperties` and overwrites the dynamic property, so the assignment is silently lost on the next request. + +This adds `__set()` to `Component.php` to route direct assignments through `setVirtualProperty()`, matching `__get()` and `__unset()`. Added tests covering roundtrip persistence, type errors on invalid assignment, and `data_set()`. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `b300bbef9320`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10704/tests/oracle.patch b/tasks/livewire__livewire-10704/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..e5814ecfdd5170b132bcb691f2a1fa3dac94dd7e --- /dev/null +++ b/tasks/livewire__livewire-10704/tests/oracle.patch @@ -0,0 +1,113 @@ +diff --git a/src/Component.php b/src/Component.php +index e6dd5427..9656679a 100644 +--- a/src/Component.php ++++ b/src/Component.php +@@ -136,6 +136,19 @@ abstract class Component + return $value; + } + ++ function __set($property, $value) ++ { ++ trigger('__set', $this, $property, $value); ++ ++ if ($this->hasVirtualProperty($property)) { ++ $this->setVirtualProperty($property, $value); ++ ++ return; ++ } ++ ++ $this->{$property} = $value; ++ } ++ + function __unset($property) + { + trigger('__unset', $this, $property); +diff --git a/src/Features/SupportVirtualProperties/UnitTest.php b/src/Features/SupportVirtualProperties/UnitTest.php +index b5749458..54ba40a1 100644 +--- a/src/Features/SupportVirtualProperties/UnitTest.php ++++ b/src/Features/SupportVirtualProperties/UnitTest.php +@@ -418,4 +418,84 @@ class UnitTest extends \Tests\TestCase + Assert::assertInstanceOf(Selection::class, $component->get('selected')); + Assert::assertSame([], $component->get('selected')->keys()); + } ++ ++ function test_a_virtual_property_can_be_assigned_directly_in_an_action() ++ { ++ $test = Livewire::test(new class extends TestComponent { ++ #[Virtual] ++ public function items(): Collection ++ { ++ return collect(['a', 'b']); ++ } ++ ++ public function replace() ++ { ++ $this->items = collect(['c', 'd']); ++ } ++ }); ++ ++ $test->call('replace'); ++ $test->call('$refresh'); ++ $test->assertSet('items', fn ($items) => $items->all() === ['c', 'd']); ++ } ++ ++ function test_assigning_an_invalid_type_to_a_virtual_property_directly_throws() ++ { ++ $this->expectException(\TypeError::class); ++ ++ $test = Livewire::test(new class extends TestComponent { ++ #[Virtual] ++ public function items(): Collection ++ { ++ return collect(['a', 'b']); ++ } ++ ++ public function invalid() ++ { ++ $this->items = 'not-a-collection'; ++ } ++ }); ++ ++ $test->call('invalid'); ++ } ++ ++ function test_a_virtual_property_can_be_assigned_using_data_set() ++ { ++ $test = Livewire::test(new class extends TestComponent { ++ #[Virtual] ++ public function items(): Collection ++ { ++ return collect(['a', 'b']); ++ } ++ ++ public function replace() ++ { ++ data_set($this, 'items', collect(['e', 'f'])); ++ } ++ }); ++ ++ $test->call('replace'); ++ $test->call('$refresh'); ++ $test->assertSet('items', fn ($items) => $items->all() === ['e', 'f']); ++ } ++ ++ function test_a_snake_case_virtual_property_can_be_assigned_directly() ++ { ++ $test = Livewire::test(new class extends TestComponent { ++ #[Virtual] ++ public function selectedItems(): Collection ++ { ++ return collect(['a']); ++ } ++ ++ public function replace() ++ { ++ $this->selected_items = collect(['b']); ++ } ++ }); ++ ++ $test->call('replace'); ++ $test->call('$refresh'); ++ $test->assertSet('selectedItems', fn ($items) => $items->all() === ['b']); ++ } + } diff --git a/tasks/livewire__livewire-10704/tests/test.sh b/tasks/livewire__livewire-10704/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..65c99530ee56fb138dfcd87e5ee46ea26c8b543b --- /dev/null +++ b/tasks/livewire__livewire-10704/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace b300bbef93209b202f268525c46b30887204e8f2 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/livewire__livewire-10704/tests/verifier.py b/tasks/livewire__livewire-10704/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/livewire__livewire-10704/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/livewire__livewire-10713/environment/Dockerfile b/tasks/livewire__livewire-10713/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..efb67ff821b31200e8ded837b7b17c9c39b18d2c --- /dev/null +++ b/tasks/livewire__livewire-10713/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/livewire/livewire.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/livewire/livewire.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/livewire/livewire.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 2f472055f9bf95c30c118c098e8f334015faac1b 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 2f472055f9bf95c30c118c098e8f334015faac1b \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 2f472055f9bf95c30c118c098e8f334015faac1b \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/livewire__livewire-10713/instruction.md b/tasks/livewire__livewire-10713/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..219974f71a8842574177ed00c82802fd6b8d8d3b --- /dev/null +++ b/tasks/livewire__livewire-10713/instruction.md @@ -0,0 +1,20 @@ +# Issue + +**Title:** [4.x] Skip redundant form rule checks during validation + +## Description + +Validating a component currently builds every form object's rules just to check whether any validation rules exist, even when component rules have already answered that question. This is the redundant work reported in [discussion #10331](https://github.com/livewire/livewire/discussions/10331). + +Only scan form rules for the missing-rules check when the component/provided rules are empty. Actual form validation still runs independently. The production change is one condition, with regression assertions added to the existing form-validation tests. + +Measured with a form's `rules()` method: + +- `$this->validate()` with component rules: three calls become two; component and form validation errors are still present. +- `$this->validate(['username' => 'required'])`: one unnecessary form-rule call becomes zero; only the explicitly requested field is validated. + +Both regression assertions failed before the change. The form-object and validation suites now pass: 130 passed, 1 existing skipped test, 596 assertions. `git diff --check` passes. No overall application speedup is claimed; this removes one redundant rules build per form from those validation calls. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `2f472055f9bf`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10713/solution/patch.diff b/tasks/livewire__livewire-10713/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..a94a3565eb6c054f9e5f2fe01856985eb9b40793 --- /dev/null +++ b/tasks/livewire__livewire-10713/solution/patch.diff @@ -0,0 +1,73 @@ +diff --git a/src/Features/SupportFormObjects/UnitTest.php b/src/Features/SupportFormObjects/UnitTest.php +index aa86a263..dc9081f5 100644 +--- a/src/Features/SupportFormObjects/UnitTest.php ++++ b/src/Features/SupportFormObjects/UnitTest.php +@@ -733,8 +733,10 @@ class UnitTest extends \Tests\TestCase + + function test_form_object_validation_runs_alongside_component_validation() + { ++ PostFormWithCountedRules::$rulesCalls = 0; ++ + Livewire::test(new class extends TestComponent { +- public PostFormValidateStub $form; ++ public PostFormWithCountedRules $form; + + #[Validate('required')] + public $username = ''; +@@ -750,12 +752,15 @@ class UnitTest extends \Tests\TestCase + ->assertHasErrors('form.content') + ->assertHasErrors('username') + ; ++ $this->assertSame(2, PostFormWithCountedRules::$rulesCalls); + } + + function test_form_object_validation_wont_run_if_rules_are_passed_into_validate() + { ++ PostFormWithCountedRules::$rulesCalls = 0; ++ + Livewire::test(new class extends TestComponent { +- public PostFormValidateStub $form; ++ public PostFormWithCountedRules $form; + + public $username = ''; + +@@ -770,6 +775,7 @@ class UnitTest extends \Tests\TestCase + ->assertHasNoErrors('form.content') + ->assertHasErrors('username') + ; ++ $this->assertSame(0, PostFormWithCountedRules::$rulesCalls); + } + + function test_allows_form_object_without_rules_without_throwing_an_error() +@@ -1310,6 +1316,18 @@ class PostFormValidateStub extends Form + ]; + } + ++class PostFormWithCountedRules extends PostFormValidateStub ++{ ++ public static $rulesCalls = 0; ++ ++ public function rules() ++ { ++ static::$rulesCalls++; ++ ++ return $this->rules; ++ } ++} ++ + class PostFormValidateOnUpdateStub extends Form + { + #[Validate] +diff --git a/src/Features/SupportValidation/HandlesValidation.php b/src/Features/SupportValidation/HandlesValidation.php +index fc83bfe8..8bcd4d08 100644 +--- a/src/Features/SupportValidation/HandlesValidation.php ++++ b/src/Features/SupportValidation/HandlesValidation.php +@@ -490,7 +490,7 @@ trait HandlesValidation + // Let's make sure there are no form objects that contain them... + $allRules = $rules; + +- if ($this->isRootComponent()) { ++ if (empty($rules) && $this->isRootComponent()) { + foreach ($this->getFormObjects() as $form) { + $allRules = array_merge($allRules, $form->getRules()); + } diff --git a/tasks/livewire__livewire-10713/solution/solve.sh b/tasks/livewire__livewire-10713/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/livewire__livewire-10713/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/livewire__livewire-10713/task.toml b/tasks/livewire__livewire-10713/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..655d9875178ea6ff5b06c6f57b6f4f0a3c3ec45a --- /dev/null +++ b/tasks/livewire__livewire-10713/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/livewire__livewire-10713" +description = "[4.x] Skip redundant form rule checks during validation" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "livewire", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "livewire/livewire" +ref = "2f472055f9bf95c30c118c098e8f334015faac1b" +reference = "https://github.com/livewire/livewire/pull/10713" +source_access = "auto" +built_at = "2026-11-16T16:09:51.481969+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:c015963f5e1030536ce0f518d3ed9dea5210c8ea310c2be82e53a954b6464956" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-15T15:18:03Z" +diff_format = "unified" +context_files = [ + "src/Features/SupportFormObjects/UnitTest.php", + "src/Features/SupportValidation/HandlesValidation.php", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 24 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.415309+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:fc3a0376e36a90b3c8f17ad970749fb800b5fe16de7cc5ad0769c0f3faec7d05" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/livewire__livewire-10713/tests/capture.py b/tasks/livewire__livewire-10713/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/livewire__livewire-10713/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/livewire__livewire-10713/tests/instruction.md b/tasks/livewire__livewire-10713/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..219974f71a8842574177ed00c82802fd6b8d8d3b --- /dev/null +++ b/tasks/livewire__livewire-10713/tests/instruction.md @@ -0,0 +1,20 @@ +# Issue + +**Title:** [4.x] Skip redundant form rule checks during validation + +## Description + +Validating a component currently builds every form object's rules just to check whether any validation rules exist, even when component rules have already answered that question. This is the redundant work reported in [discussion #10331](https://github.com/livewire/livewire/discussions/10331). + +Only scan form rules for the missing-rules check when the component/provided rules are empty. Actual form validation still runs independently. The production change is one condition, with regression assertions added to the existing form-validation tests. + +Measured with a form's `rules()` method: + +- `$this->validate()` with component rules: three calls become two; component and form validation errors are still present. +- `$this->validate(['username' => 'required'])`: one unnecessary form-rule call becomes zero; only the explicitly requested field is validated. + +Both regression assertions failed before the change. The form-object and validation suites now pass: 130 passed, 1 existing skipped test, 596 assertions. `git diff --check` passes. No overall application speedup is claimed; this removes one redundant rules build per form from those validation calls. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `2f472055f9bf`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10713/tests/oracle.patch b/tasks/livewire__livewire-10713/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..a94a3565eb6c054f9e5f2fe01856985eb9b40793 --- /dev/null +++ b/tasks/livewire__livewire-10713/tests/oracle.patch @@ -0,0 +1,73 @@ +diff --git a/src/Features/SupportFormObjects/UnitTest.php b/src/Features/SupportFormObjects/UnitTest.php +index aa86a263..dc9081f5 100644 +--- a/src/Features/SupportFormObjects/UnitTest.php ++++ b/src/Features/SupportFormObjects/UnitTest.php +@@ -733,8 +733,10 @@ class UnitTest extends \Tests\TestCase + + function test_form_object_validation_runs_alongside_component_validation() + { ++ PostFormWithCountedRules::$rulesCalls = 0; ++ + Livewire::test(new class extends TestComponent { +- public PostFormValidateStub $form; ++ public PostFormWithCountedRules $form; + + #[Validate('required')] + public $username = ''; +@@ -750,12 +752,15 @@ class UnitTest extends \Tests\TestCase + ->assertHasErrors('form.content') + ->assertHasErrors('username') + ; ++ $this->assertSame(2, PostFormWithCountedRules::$rulesCalls); + } + + function test_form_object_validation_wont_run_if_rules_are_passed_into_validate() + { ++ PostFormWithCountedRules::$rulesCalls = 0; ++ + Livewire::test(new class extends TestComponent { +- public PostFormValidateStub $form; ++ public PostFormWithCountedRules $form; + + public $username = ''; + +@@ -770,6 +775,7 @@ class UnitTest extends \Tests\TestCase + ->assertHasNoErrors('form.content') + ->assertHasErrors('username') + ; ++ $this->assertSame(0, PostFormWithCountedRules::$rulesCalls); + } + + function test_allows_form_object_without_rules_without_throwing_an_error() +@@ -1310,6 +1316,18 @@ class PostFormValidateStub extends Form + ]; + } + ++class PostFormWithCountedRules extends PostFormValidateStub ++{ ++ public static $rulesCalls = 0; ++ ++ public function rules() ++ { ++ static::$rulesCalls++; ++ ++ return $this->rules; ++ } ++} ++ + class PostFormValidateOnUpdateStub extends Form + { + #[Validate] +diff --git a/src/Features/SupportValidation/HandlesValidation.php b/src/Features/SupportValidation/HandlesValidation.php +index fc83bfe8..8bcd4d08 100644 +--- a/src/Features/SupportValidation/HandlesValidation.php ++++ b/src/Features/SupportValidation/HandlesValidation.php +@@ -490,7 +490,7 @@ trait HandlesValidation + // Let's make sure there are no form objects that contain them... + $allRules = $rules; + +- if ($this->isRootComponent()) { ++ if (empty($rules) && $this->isRootComponent()) { + foreach ($this->getFormObjects() as $form) { + $allRules = array_merge($allRules, $form->getRules()); + } diff --git a/tasks/livewire__livewire-10713/tests/test.sh b/tasks/livewire__livewire-10713/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..d1f803bcc5adfb8838b193a1522e2a78e124ab64 --- /dev/null +++ b/tasks/livewire__livewire-10713/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 2f472055f9bf95c30c118c098e8f334015faac1b > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/livewire__livewire-10713/tests/verifier.py b/tasks/livewire__livewire-10713/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/livewire__livewire-10713/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/livewire__livewire-10714/environment/Dockerfile b/tasks/livewire__livewire-10714/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..db4ff61924bf6a3fa30c58ba6fec44bb59f1f510 --- /dev/null +++ b/tasks/livewire__livewire-10714/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/livewire/livewire.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/livewire/livewire.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/livewire/livewire.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 76e1b05146c843256d2a30fa843fce1e365b04c0 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 76e1b05146c843256d2a30fa843fce1e365b04c0 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 76e1b05146c843256d2a30fa843fce1e365b04c0 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/livewire__livewire-10714/instruction.md b/tasks/livewire__livewire-10714/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..82146c5259403b6f3be81753e8b59a7a26261960 --- /dev/null +++ b/tasks/livewire__livewire-10714/instruction.md @@ -0,0 +1,23 @@ +# Issue + +**Title:** [4.x] Add assertions for skipped component rendering + +## Description + +Developers currently have to infer whether an action skipped rendering from unchanged state or HTML, which can also happen after a normal render. In #10087, a notification badge needs to prove that an event for another notification skips rendering. + +Adds fluent `assertRenderSkipped()` and `assertRenderNotSkipped()` assertions using the latest component's existing render state. Covers `skipRender()`, `#[Renderless]`, replacement HTML, consecutive requests, and failed requests. Includes a usage example and testing reference entries. No component runtime changes. + +Source: https://github.com/livewire/livewire/discussions/10087 + +Validation: 68 tests passed, 251 assertions on PHP 8.4.6 / Laravel 13.31.0: + +```sh +vendor/bin/phpunit src/Features/SupportTesting/UnitTest.php src/Mechanisms/Tests/ComponentSkipRenderUnitTest.php +``` + +The new tests failed on the missing API before implementation. Browser behavior is unchanged. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `76e1b05146c8`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10714/solution/patch.diff b/tasks/livewire__livewire-10714/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..63c2a4538e9a2a323159f87ad13399883e216c92 --- /dev/null +++ b/tasks/livewire__livewire-10714/solution/patch.diff @@ -0,0 +1,179 @@ +diff --git a/docs/testing.md b/docs/testing.md +index 5536e863..e85e80c8 100644 +--- a/docs/testing.md ++++ b/docs/testing.md +@@ -401,6 +401,20 @@ it('dispatches event with correct data', function () { + }); + ``` + ++### Testing skipped rendering ++ ++Use `assertRenderSkipped()` to verify that an action or event listener skipped rendering with `$this->skipRender()` or `#[Renderless]`. For example, a notification badge might skip rendering when it receives an event for another notification: ++ ++```php ++it('skips rendering for unrelated notifications', function () { ++ Livewire::test('notification-badge', ['notificationId' => 1]) ++ ->dispatch('notification-read', notificationId: 999) ++ ->assertRenderSkipped(); ++}); ++``` ++ ++Use `assertRenderNotSkipped()` to verify that rendering ran, even if the resulting HTML is unchanged. Both assertions check the latest request. Providing replacement HTML to `skipRender()` still counts as skipping the component's rendering. ++ + ### Testing JS evaluation + + Assert that a component evaluated JavaScript via `$this->js()`: +@@ -501,6 +515,8 @@ Below is a comprehensive reference of every Livewire testing method available to + | `assertSet('title', '...')` | Assert that a property equals the provided value | + | `assertNotSet('title', '...')` | Assert that a property does not equal the provided value | + | `assertCount('posts', 3)` | Assert that a property contains 3 items | ++| `assertRenderSkipped()` | Assert that component rendering was skipped during the latest request | ++| `assertRenderNotSkipped()` | Assert that component rendering was not skipped during the latest request | + | `assertSee('...')` | Assert that the rendered HTML contains the provided text | + | `assertDontSee('...')` | Assert that the rendered HTML does not contain the provided text | + | `assertSeeHtml('
...
')` | Assert that raw HTML is present in the rendered output | +diff --git a/src/Features/SupportTesting/MakesAssertions.php b/src/Features/SupportTesting/MakesAssertions.php +index 8d9e62e4..d5a7a4a2 100644 +--- a/src/Features/SupportTesting/MakesAssertions.php ++++ b/src/Features/SupportTesting/MakesAssertions.php +@@ -8,6 +8,36 @@ use Illuminate\Support\Arr; + + trait MakesAssertions + { ++ /** ++ * @return $this ++ */ ++ function assertRenderSkipped() ++ { ++ $this->lastState->getResponse()->assertOk(); ++ ++ PHPUnit::assertTrue( ++ (bool) $this->instance()->shouldSkipRender(), ++ 'Failed asserting that component rendering was skipped.' ++ ); ++ ++ return $this; ++ } ++ ++ /** ++ * @return $this ++ */ ++ function assertRenderNotSkipped() ++ { ++ $this->lastState->getResponse()->assertOk(); ++ ++ PHPUnit::assertFalse( ++ (bool) $this->instance()->shouldSkipRender(), ++ 'Failed asserting that component rendering was not skipped.' ++ ); ++ ++ return $this; ++ } ++ + /** + * @return $this + */ +diff --git a/src/Features/SupportTesting/UnitTest.php b/src/Features/SupportTesting/UnitTest.php +index 5d9e317f..4a818eb4 100644 +--- a/src/Features/SupportTesting/UnitTest.php ++++ b/src/Features/SupportTesting/UnitTest.php +@@ -16,6 +16,65 @@ use Tests\TestComponent; + + class UnitTest extends \LegacyTests\Unit\TestCase + { ++ function test_render_assertions_follow_the_latest_request() ++ { ++ Livewire::test(NotificationBadgeForRenderAssertions::class) ++ ->assertRenderNotSkipped() ++ ->call('$refresh') ++ ->assertRenderNotSkipped() ++ ->dispatch('notification-read', notificationId: 999) ++ ->assertRenderSkipped() ++ ->assertSet('count', 1) ++ ->dispatch('notification-read', notificationId: 1) ++ ->assertRenderNotSkipped() ++ ->assertSet('count', 0) ++ ->call('renderlessAction') ++ ->assertRenderSkipped() ++ ->call('$refresh') ++ ->assertRenderNotSkipped() ++ ->call('replaceHtml') ++ ->assertRenderSkipped() ++ ->assertSee('Replacement'); ++ } ++ ++ function test_render_skipped_assertion_fails_when_rendering_was_not_skipped() ++ { ++ $this->expectException(ExpectationFailedException::class); ++ $this->expectExceptionMessage('Failed asserting that component rendering was skipped.'); ++ ++ Livewire::test(NotificationBadgeForRenderAssertions::class) ++ ->call('$refresh') ++ ->assertRenderSkipped(); ++ } ++ ++ function test_render_not_skipped_assertion_fails_when_rendering_was_skipped() ++ { ++ $this->expectException(ExpectationFailedException::class); ++ $this->expectExceptionMessage('Failed asserting that component rendering was not skipped.'); ++ ++ Livewire::test(NotificationBadgeForRenderAssertions::class) ++ ->dispatch('notification-read', notificationId: 999) ++ ->assertRenderNotSkipped(); ++ } ++ ++ function test_render_skipped_assertion_does_not_pass_for_a_failed_request() ++ { ++ $this->expectException(ExpectationFailedException::class); ++ ++ Livewire::test(NotificationBadgeForRenderAssertions::class) ++ ->call('forbidden') ++ ->assertRenderSkipped(); ++ } ++ ++ function test_render_not_skipped_assertion_does_not_pass_for_a_failed_request() ++ { ++ $this->expectException(ExpectationFailedException::class); ++ ++ Livewire::test(NotificationBadgeForRenderAssertions::class) ++ ->call('forbidden') ++ ->assertRenderNotSkipped(); ++ } ++ + function test_can_assert_see_livewire_on_standard_blade_view() + { + Artisan::call('make:livewire', ['name' => 'foo', '--class' => true]); +@@ -876,3 +935,33 @@ enum BackedFooBarEnum : string + case FOO = 'foo'; + case BAR = 'bar'; + } ++ ++class NotificationBadgeForRenderAssertions extends TestComponent ++{ ++ public $notificationId = 1; ++ public $count = 1; ++ ++ #[\Livewire\Attributes\On('notification-read')] ++ public function markAsRead($notificationId) ++ { ++ if ($notificationId !== $this->notificationId) { ++ $this->skipRender(); ++ return; ++ } ++ ++ $this->count = 0; ++ } ++ ++ #[\Livewire\Attributes\Renderless] ++ public function renderlessAction() {} ++ ++ public function replaceHtml() ++ { ++ $this->skipRender('
Replacement
'); ++ } ++ ++ public function forbidden() ++ { ++ abort(403); ++ } ++} diff --git a/tasks/livewire__livewire-10714/solution/solve.sh b/tasks/livewire__livewire-10714/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/livewire__livewire-10714/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/livewire__livewire-10714/task.toml b/tasks/livewire__livewire-10714/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..5ae4fe11a649e0ccb546465f391e0d3536271b84 --- /dev/null +++ b/tasks/livewire__livewire-10714/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/livewire__livewire-10714" +description = "[4.x] Add assertions for skipped component rendering" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "livewire", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "livewire/livewire" +ref = "76e1b05146c843256d2a30fa843fce1e365b04c0" +reference = "https://github.com/livewire/livewire/pull/10714" +source_access = "auto" +built_at = "2026-11-16T16:09:51.480404+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:a3e2fc25772c6c20c344a954dd3dcb506ae5023dac58c2d3c3e5f3a7215f3675" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-15T15:34:27Z" +diff_format = "unified" +context_files = [ + "docs/testing.md", + "src/Features/SupportTesting/MakesAssertions.php", + "src/Features/SupportTesting/UnitTest.php", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 135 +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.415991+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:8a8815da63a529432ddbb98b38ab76b0ecfec0ec08e2517ef9f76148fb1d555f" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/livewire__livewire-10714/tests/capture.py b/tasks/livewire__livewire-10714/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/livewire__livewire-10714/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/livewire__livewire-10714/tests/instruction.md b/tasks/livewire__livewire-10714/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..82146c5259403b6f3be81753e8b59a7a26261960 --- /dev/null +++ b/tasks/livewire__livewire-10714/tests/instruction.md @@ -0,0 +1,23 @@ +# Issue + +**Title:** [4.x] Add assertions for skipped component rendering + +## Description + +Developers currently have to infer whether an action skipped rendering from unchanged state or HTML, which can also happen after a normal render. In #10087, a notification badge needs to prove that an event for another notification skips rendering. + +Adds fluent `assertRenderSkipped()` and `assertRenderNotSkipped()` assertions using the latest component's existing render state. Covers `skipRender()`, `#[Renderless]`, replacement HTML, consecutive requests, and failed requests. Includes a usage example and testing reference entries. No component runtime changes. + +Source: https://github.com/livewire/livewire/discussions/10087 + +Validation: 68 tests passed, 251 assertions on PHP 8.4.6 / Laravel 13.31.0: + +```sh +vendor/bin/phpunit src/Features/SupportTesting/UnitTest.php src/Mechanisms/Tests/ComponentSkipRenderUnitTest.php +``` + +The new tests failed on the missing API before implementation. Browser behavior is unchanged. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `76e1b05146c8`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10714/tests/oracle.patch b/tasks/livewire__livewire-10714/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..63c2a4538e9a2a323159f87ad13399883e216c92 --- /dev/null +++ b/tasks/livewire__livewire-10714/tests/oracle.patch @@ -0,0 +1,179 @@ +diff --git a/docs/testing.md b/docs/testing.md +index 5536e863..e85e80c8 100644 +--- a/docs/testing.md ++++ b/docs/testing.md +@@ -401,6 +401,20 @@ it('dispatches event with correct data', function () { + }); + ``` + ++### Testing skipped rendering ++ ++Use `assertRenderSkipped()` to verify that an action or event listener skipped rendering with `$this->skipRender()` or `#[Renderless]`. For example, a notification badge might skip rendering when it receives an event for another notification: ++ ++```php ++it('skips rendering for unrelated notifications', function () { ++ Livewire::test('notification-badge', ['notificationId' => 1]) ++ ->dispatch('notification-read', notificationId: 999) ++ ->assertRenderSkipped(); ++}); ++``` ++ ++Use `assertRenderNotSkipped()` to verify that rendering ran, even if the resulting HTML is unchanged. Both assertions check the latest request. Providing replacement HTML to `skipRender()` still counts as skipping the component's rendering. ++ + ### Testing JS evaluation + + Assert that a component evaluated JavaScript via `$this->js()`: +@@ -501,6 +515,8 @@ Below is a comprehensive reference of every Livewire testing method available to + | `assertSet('title', '...')` | Assert that a property equals the provided value | + | `assertNotSet('title', '...')` | Assert that a property does not equal the provided value | + | `assertCount('posts', 3)` | Assert that a property contains 3 items | ++| `assertRenderSkipped()` | Assert that component rendering was skipped during the latest request | ++| `assertRenderNotSkipped()` | Assert that component rendering was not skipped during the latest request | + | `assertSee('...')` | Assert that the rendered HTML contains the provided text | + | `assertDontSee('...')` | Assert that the rendered HTML does not contain the provided text | + | `assertSeeHtml('
...
')` | Assert that raw HTML is present in the rendered output | +diff --git a/src/Features/SupportTesting/MakesAssertions.php b/src/Features/SupportTesting/MakesAssertions.php +index 8d9e62e4..d5a7a4a2 100644 +--- a/src/Features/SupportTesting/MakesAssertions.php ++++ b/src/Features/SupportTesting/MakesAssertions.php +@@ -8,6 +8,36 @@ use Illuminate\Support\Arr; + + trait MakesAssertions + { ++ /** ++ * @return $this ++ */ ++ function assertRenderSkipped() ++ { ++ $this->lastState->getResponse()->assertOk(); ++ ++ PHPUnit::assertTrue( ++ (bool) $this->instance()->shouldSkipRender(), ++ 'Failed asserting that component rendering was skipped.' ++ ); ++ ++ return $this; ++ } ++ ++ /** ++ * @return $this ++ */ ++ function assertRenderNotSkipped() ++ { ++ $this->lastState->getResponse()->assertOk(); ++ ++ PHPUnit::assertFalse( ++ (bool) $this->instance()->shouldSkipRender(), ++ 'Failed asserting that component rendering was not skipped.' ++ ); ++ ++ return $this; ++ } ++ + /** + * @return $this + */ +diff --git a/src/Features/SupportTesting/UnitTest.php b/src/Features/SupportTesting/UnitTest.php +index 5d9e317f..4a818eb4 100644 +--- a/src/Features/SupportTesting/UnitTest.php ++++ b/src/Features/SupportTesting/UnitTest.php +@@ -16,6 +16,65 @@ use Tests\TestComponent; + + class UnitTest extends \LegacyTests\Unit\TestCase + { ++ function test_render_assertions_follow_the_latest_request() ++ { ++ Livewire::test(NotificationBadgeForRenderAssertions::class) ++ ->assertRenderNotSkipped() ++ ->call('$refresh') ++ ->assertRenderNotSkipped() ++ ->dispatch('notification-read', notificationId: 999) ++ ->assertRenderSkipped() ++ ->assertSet('count', 1) ++ ->dispatch('notification-read', notificationId: 1) ++ ->assertRenderNotSkipped() ++ ->assertSet('count', 0) ++ ->call('renderlessAction') ++ ->assertRenderSkipped() ++ ->call('$refresh') ++ ->assertRenderNotSkipped() ++ ->call('replaceHtml') ++ ->assertRenderSkipped() ++ ->assertSee('Replacement'); ++ } ++ ++ function test_render_skipped_assertion_fails_when_rendering_was_not_skipped() ++ { ++ $this->expectException(ExpectationFailedException::class); ++ $this->expectExceptionMessage('Failed asserting that component rendering was skipped.'); ++ ++ Livewire::test(NotificationBadgeForRenderAssertions::class) ++ ->call('$refresh') ++ ->assertRenderSkipped(); ++ } ++ ++ function test_render_not_skipped_assertion_fails_when_rendering_was_skipped() ++ { ++ $this->expectException(ExpectationFailedException::class); ++ $this->expectExceptionMessage('Failed asserting that component rendering was not skipped.'); ++ ++ Livewire::test(NotificationBadgeForRenderAssertions::class) ++ ->dispatch('notification-read', notificationId: 999) ++ ->assertRenderNotSkipped(); ++ } ++ ++ function test_render_skipped_assertion_does_not_pass_for_a_failed_request() ++ { ++ $this->expectException(ExpectationFailedException::class); ++ ++ Livewire::test(NotificationBadgeForRenderAssertions::class) ++ ->call('forbidden') ++ ->assertRenderSkipped(); ++ } ++ ++ function test_render_not_skipped_assertion_does_not_pass_for_a_failed_request() ++ { ++ $this->expectException(ExpectationFailedException::class); ++ ++ Livewire::test(NotificationBadgeForRenderAssertions::class) ++ ->call('forbidden') ++ ->assertRenderNotSkipped(); ++ } ++ + function test_can_assert_see_livewire_on_standard_blade_view() + { + Artisan::call('make:livewire', ['name' => 'foo', '--class' => true]); +@@ -876,3 +935,33 @@ enum BackedFooBarEnum : string + case FOO = 'foo'; + case BAR = 'bar'; + } ++ ++class NotificationBadgeForRenderAssertions extends TestComponent ++{ ++ public $notificationId = 1; ++ public $count = 1; ++ ++ #[\Livewire\Attributes\On('notification-read')] ++ public function markAsRead($notificationId) ++ { ++ if ($notificationId !== $this->notificationId) { ++ $this->skipRender(); ++ return; ++ } ++ ++ $this->count = 0; ++ } ++ ++ #[\Livewire\Attributes\Renderless] ++ public function renderlessAction() {} ++ ++ public function replaceHtml() ++ { ++ $this->skipRender('
Replacement
'); ++ } ++ ++ public function forbidden() ++ { ++ abort(403); ++ } ++} diff --git a/tasks/livewire__livewire-10714/tests/test.sh b/tasks/livewire__livewire-10714/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..15ec7a8f8a40437a539e40b6cbf790982f553833 --- /dev/null +++ b/tasks/livewire__livewire-10714/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 76e1b05146c843256d2a30fa843fce1e365b04c0 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/livewire__livewire-10714/tests/verifier.py b/tasks/livewire__livewire-10714/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/livewire__livewire-10714/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/livewire__livewire-10715/environment/Dockerfile b/tasks/livewire__livewire-10715/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..20e91b55d57345a384a5a13b18b2e59197b3b89d --- /dev/null +++ b/tasks/livewire__livewire-10715/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/livewire/livewire.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/livewire/livewire.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/livewire/livewire.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 90f8b72e860421f5f5ddde1330263aa657a29a0f 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 90f8b72e860421f5f5ddde1330263aa657a29a0f \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 90f8b72e860421f5f5ddde1330263aa657a29a0f \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/livewire__livewire-10715/instruction.md b/tasks/livewire__livewire-10715/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..05d6b17db833d16c7a4cab6c01d1398163bc96e4 --- /dev/null +++ b/tasks/livewire__livewire-10715/instruction.md @@ -0,0 +1,28 @@ +# Issue + +**Title:** [4.x] Check all matching events in callback assertions + +## Description + +When a component dispatches the same event twice, `assertDispatched()` with a callback only checks the first occurrence. For example, after dispatching `foo(id: 1)` and `foo(id: 2)`, these equivalent assertions disagree: + +```php +$component->assertDispatched('foo', id: 2); // Passes +$component->assertDispatched('foo', fn ($event, $params) => $params['id'] === 2); // Fails +``` + +The inverse callback assertion, `assertNotDispatched()`, also incorrectly passes for that second event. This changes callback matching to search all events with the requested name and stop at the first match, consistent with named-parameter assertions. + +Related report: https://github.com/livewire/livewire/discussions/8614. Its general concern is inconsistent parameter matching; the reproducible case addressed here is multiple occurrences of the same event with a callback. Credit to @utsavsomaiya, who previously proposed this fix as part of the closed #10046. This PR isolates that bug fix with regression coverage. + +Both new regression tests failed before the change. Afterward, the event and testing suites pass: **77 tests, 269 assertions**, PHP 8.4.6 / Laravel 13.31.0. + +```sh +vendor/bin/phpunit src/Features/SupportEvents/UnitTest.php src/Features/SupportTesting/UnitTest.php +``` + +Coverage includes matching first and later occurrences, ignoring other event names, missing events, and rejecting `assertNotDispatched()` when a later occurrence matches. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `90f8b72e8604`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10715/solution/patch.diff b/tasks/livewire__livewire-10715/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..f3b35ff187dd779b2465d53c5a687e6c34d9b2a3 --- /dev/null +++ b/tasks/livewire__livewire-10715/solution/patch.diff @@ -0,0 +1,64 @@ +diff --git a/src/Features/SupportEvents/TestsEvents.php b/src/Features/SupportEvents/TestsEvents.php +index 8f19a219..a75ec743 100644 +--- a/src/Features/SupportEvents/TestsEvents.php ++++ b/src/Features/SupportEvents/TestsEvents.php +@@ -51,11 +51,9 @@ trait TestsEvents + if (empty($params)) { + $test = collect(data_get($this->effects, 'dispatches'))->contains('name', '=', $value); + } elseif (isset($params[0]) && ! is_string($params[0]) && is_callable($params[0])) { +- $event = collect(data_get($this->effects, 'dispatches'))->first(function ($item) use ($value) { +- return $item['name'] === $value; ++ $test = collect(data_get($this->effects, 'dispatches'))->contains(function ($item) use ($value, $params) { ++ return $item['name'] === $value && $params[0]($item['name'], $item['params']); + }); +- +- $test = $event && $params[0]($event['name'], $event['params']); + } else { + $test = (bool) collect(data_get($this->effects, 'dispatches'))->first(function ($item) use ($value, $params) { + $commonParams = array_intersect_key($item['params'], $params); +diff --git a/src/Features/SupportEvents/UnitTest.php b/src/Features/SupportEvents/UnitTest.php +index 40fcc721..af17f840 100644 +--- a/src/Features/SupportEvents/UnitTest.php ++++ b/src/Features/SupportEvents/UnitTest.php +@@ -79,6 +79,41 @@ class UnitTest extends \Tests\TestCase + ; + } + ++ public function test_dispatch_callback_can_match_any_event_with_the_given_name() ++ { ++ Livewire::test(new class extends TestComponent { ++ public function dispatchFoo() ++ { ++ $this->dispatch('foo', id: 1); ++ $this->dispatch('foo', id: 2); ++ $this->dispatch('bar', id: 3); ++ } ++ }) ++ ->call('dispatchFoo') ++ ->assertDispatched('bar', id: 3) ++ ->assertDispatched('foo', id: 2) ++ ->assertNotDispatched('foo', fn ($event, $params) => $params['id'] === 3) ++ ->assertNotDispatched('missing', fn () => true) ++ ->assertDispatched('foo', fn ($event, $params) => $event === 'foo' && $params['id'] === 1) ++ ->assertDispatched('foo', fn ($event, $params) => $event === 'foo' && $params['id'] === 2); ++ } ++ ++ public function test_not_dispatched_callback_fails_when_a_later_event_matches() ++ { ++ $component = Livewire::test(new class extends TestComponent { ++ public function dispatchFoo() ++ { ++ $this->dispatch('foo', id: 1); ++ $this->dispatch('foo', id: 2); ++ } ++ })->call('dispatchFoo'); ++ ++ $this->expectException(\PHPUnit\Framework\ExpectationFailedException::class); ++ $this->expectExceptionMessage('Failed asserting that an event [foo] was not fired.'); ++ ++ $component->assertNotDispatched('foo', fn ($event, $params) => $params['id'] === 2); ++ } ++ + public function test_it_can_register_multiple_listeners_via_attribute(): void + { + Livewire::test(new class extends TestComponent { diff --git a/tasks/livewire__livewire-10715/solution/solve.sh b/tasks/livewire__livewire-10715/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/livewire__livewire-10715/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/livewire__livewire-10715/task.toml b/tasks/livewire__livewire-10715/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..c97cba135bd67a31aca3f9b394b81724668936de --- /dev/null +++ b/tasks/livewire__livewire-10715/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/livewire__livewire-10715" +description = "[4.x] Check all matching events in callback assertions" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "livewire", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "livewire/livewire" +ref = "90f8b72e860421f5f5ddde1330263aa657a29a0f" +reference = "https://github.com/livewire/livewire/pull/10715" +source_access = "auto" +built_at = "2026-11-16T16:09:51.478877+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:b47200099f773371bff492d589bd4f63786c763b9853e33a8873b1694828d117" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-15T15:42:59Z" +diff_format = "unified" +context_files = [ + "src/Features/SupportEvents/TestsEvents.php", + "src/Features/SupportEvents/UnitTest.php", +] +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.416627+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:1360d0bc1cd3f67f3ef562f3d868c7f252c5e07f0e2eb2737d26194b378e6afd" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/livewire__livewire-10715/tests/capture.py b/tasks/livewire__livewire-10715/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/livewire__livewire-10715/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/livewire__livewire-10715/tests/instruction.md b/tasks/livewire__livewire-10715/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..05d6b17db833d16c7a4cab6c01d1398163bc96e4 --- /dev/null +++ b/tasks/livewire__livewire-10715/tests/instruction.md @@ -0,0 +1,28 @@ +# Issue + +**Title:** [4.x] Check all matching events in callback assertions + +## Description + +When a component dispatches the same event twice, `assertDispatched()` with a callback only checks the first occurrence. For example, after dispatching `foo(id: 1)` and `foo(id: 2)`, these equivalent assertions disagree: + +```php +$component->assertDispatched('foo', id: 2); // Passes +$component->assertDispatched('foo', fn ($event, $params) => $params['id'] === 2); // Fails +``` + +The inverse callback assertion, `assertNotDispatched()`, also incorrectly passes for that second event. This changes callback matching to search all events with the requested name and stop at the first match, consistent with named-parameter assertions. + +Related report: https://github.com/livewire/livewire/discussions/8614. Its general concern is inconsistent parameter matching; the reproducible case addressed here is multiple occurrences of the same event with a callback. Credit to @utsavsomaiya, who previously proposed this fix as part of the closed #10046. This PR isolates that bug fix with regression coverage. + +Both new regression tests failed before the change. Afterward, the event and testing suites pass: **77 tests, 269 assertions**, PHP 8.4.6 / Laravel 13.31.0. + +```sh +vendor/bin/phpunit src/Features/SupportEvents/UnitTest.php src/Features/SupportTesting/UnitTest.php +``` + +Coverage includes matching first and later occurrences, ignoring other event names, missing events, and rejecting `assertNotDispatched()` when a later occurrence matches. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `90f8b72e8604`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10715/tests/oracle.patch b/tasks/livewire__livewire-10715/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..f3b35ff187dd779b2465d53c5a687e6c34d9b2a3 --- /dev/null +++ b/tasks/livewire__livewire-10715/tests/oracle.patch @@ -0,0 +1,64 @@ +diff --git a/src/Features/SupportEvents/TestsEvents.php b/src/Features/SupportEvents/TestsEvents.php +index 8f19a219..a75ec743 100644 +--- a/src/Features/SupportEvents/TestsEvents.php ++++ b/src/Features/SupportEvents/TestsEvents.php +@@ -51,11 +51,9 @@ trait TestsEvents + if (empty($params)) { + $test = collect(data_get($this->effects, 'dispatches'))->contains('name', '=', $value); + } elseif (isset($params[0]) && ! is_string($params[0]) && is_callable($params[0])) { +- $event = collect(data_get($this->effects, 'dispatches'))->first(function ($item) use ($value) { +- return $item['name'] === $value; ++ $test = collect(data_get($this->effects, 'dispatches'))->contains(function ($item) use ($value, $params) { ++ return $item['name'] === $value && $params[0]($item['name'], $item['params']); + }); +- +- $test = $event && $params[0]($event['name'], $event['params']); + } else { + $test = (bool) collect(data_get($this->effects, 'dispatches'))->first(function ($item) use ($value, $params) { + $commonParams = array_intersect_key($item['params'], $params); +diff --git a/src/Features/SupportEvents/UnitTest.php b/src/Features/SupportEvents/UnitTest.php +index 40fcc721..af17f840 100644 +--- a/src/Features/SupportEvents/UnitTest.php ++++ b/src/Features/SupportEvents/UnitTest.php +@@ -79,6 +79,41 @@ class UnitTest extends \Tests\TestCase + ; + } + ++ public function test_dispatch_callback_can_match_any_event_with_the_given_name() ++ { ++ Livewire::test(new class extends TestComponent { ++ public function dispatchFoo() ++ { ++ $this->dispatch('foo', id: 1); ++ $this->dispatch('foo', id: 2); ++ $this->dispatch('bar', id: 3); ++ } ++ }) ++ ->call('dispatchFoo') ++ ->assertDispatched('bar', id: 3) ++ ->assertDispatched('foo', id: 2) ++ ->assertNotDispatched('foo', fn ($event, $params) => $params['id'] === 3) ++ ->assertNotDispatched('missing', fn () => true) ++ ->assertDispatched('foo', fn ($event, $params) => $event === 'foo' && $params['id'] === 1) ++ ->assertDispatched('foo', fn ($event, $params) => $event === 'foo' && $params['id'] === 2); ++ } ++ ++ public function test_not_dispatched_callback_fails_when_a_later_event_matches() ++ { ++ $component = Livewire::test(new class extends TestComponent { ++ public function dispatchFoo() ++ { ++ $this->dispatch('foo', id: 1); ++ $this->dispatch('foo', id: 2); ++ } ++ })->call('dispatchFoo'); ++ ++ $this->expectException(\PHPUnit\Framework\ExpectationFailedException::class); ++ $this->expectExceptionMessage('Failed asserting that an event [foo] was not fired.'); ++ ++ $component->assertNotDispatched('foo', fn ($event, $params) => $params['id'] === 2); ++ } ++ + public function test_it_can_register_multiple_listeners_via_attribute(): void + { + Livewire::test(new class extends TestComponent { diff --git a/tasks/livewire__livewire-10715/tests/test.sh b/tasks/livewire__livewire-10715/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..db97d250e9694e56221de0ce2aa13cd42b9b739e --- /dev/null +++ b/tasks/livewire__livewire-10715/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 90f8b72e860421f5f5ddde1330263aa657a29a0f > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/livewire__livewire-10715/tests/verifier.py b/tasks/livewire__livewire-10715/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/livewire__livewire-10715/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/livewire__livewire-10716/environment/Dockerfile b/tasks/livewire__livewire-10716/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..7bcbee78fca7613bb0c87982f85eee4809a3f3df --- /dev/null +++ b/tasks/livewire__livewire-10716/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/livewire/livewire.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/livewire/livewire.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/livewire/livewire.git +WORKDIR /workspace +RUN git fetch --depth 1 origin de2bd6f28f587ea2865c67f744b2a7b372c1ec4a 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard de2bd6f28f587ea2865c67f744b2a7b372c1ec4a \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base de2bd6f28f587ea2865c67f744b2a7b372c1ec4a \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/livewire__livewire-10716/instruction.md b/tasks/livewire__livewire-10716/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1a8a583b6a88543e909a2786cff905fcabed5a23 --- /dev/null +++ b/tasks/livewire__livewire-10716/instruction.md @@ -0,0 +1,28 @@ +# Issue + +**Title:** [4.x] Preserve Livewire test types after response assertions + +## Description + +PHPStan reports `Call to an undefined method Illuminate\Testing\TestResponse::set()` for a valid Livewire test chain: + +```php +Livewire::test(Edit::class) + ->assertSuccessful() + ->set('foo', 'bar'); +``` + +Reported in https://github.com/livewire/livewire/discussions/6958 and reproduced on current 4.x with PHPStan 2.2.14. `Testable` mixes in Laravel's `TestResponse`, so its HTTP assertions inherit the response return type. At runtime, `Testable::__call()` forwards the assertion and returns the Livewire test instance instead. + +Adds three `@method $this` declarations for `assertSuccessful()`, `assertOk()`, and `assertStatus()` to describe that existing behavior. The component's generic type is retained after chaining. This addresses response-assertion chaining; the separate `actingAs()->test()` template-inference concern in the discussion is outside this patch. + +Validation: + +- A PHPStan level-8 fixture checks the original facade example, all three assertion-to-`set()` chains, and preservation of `Testable`. Five errors before the declarations, no errors afterward. No suppressions or casts. +- Existing testing/status-code suites plus a local runtime check: **63 tests passed, 245 assertions** on PHP 8.4.6 / Laravel 13.31.0. The runtime check verifies each assertion returns the identical `Testable` instance and the chain can still set a property. + +The patch changes only PHPDoc. The verification fixtures remain outside the package; no new test tooling or runtime code is introduced. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `de2bd6f28f58`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10716/solution/patch.diff b/tasks/livewire__livewire-10716/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..42cb07bbdca128cd56584531d8ed25f12ff465f3 --- /dev/null +++ b/tasks/livewire__livewire-10716/solution/patch.diff @@ -0,0 +1,15 @@ +diff --git a/src/Features/SupportTesting/Testable.php b/src/Features/SupportTesting/Testable.php +index fab583d6..e0dbc915 100644 +--- a/src/Features/SupportTesting/Testable.php ++++ b/src/Features/SupportTesting/Testable.php +@@ -13,6 +13,10 @@ use BackedEnum; + /** + * @template TComponent of \Livewire\Component + * ++ * @method $this assertSuccessful() ++ * @method $this assertOk() ++ * @method $this assertStatus(int $status) ++ * + * @mixin \Illuminate\Testing\TestResponse + */ + diff --git a/tasks/livewire__livewire-10716/solution/solve.sh b/tasks/livewire__livewire-10716/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/livewire__livewire-10716/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/livewire__livewire-10716/task.toml b/tasks/livewire__livewire-10716/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..1d408e99be7f54cc2429dde32e9299f07e3b99db --- /dev/null +++ b/tasks/livewire__livewire-10716/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/livewire__livewire-10716" +description = "[4.x] Preserve Livewire test types after response assertions" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "livewire", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "livewire/livewire" +ref = "de2bd6f28f587ea2865c67f744b2a7b372c1ec4a" +reference = "https://github.com/livewire/livewire/pull/10716" +source_access = "auto" +built_at = "2026-11-16T16:09:51.475756+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:7ec3594eb5e8be77e52b5ae0f82769dd4ec32533915e79e24979de763fb9f014" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-16T13:50:52Z" +diff_format = "unified" +context_files = [ + "src/Features/SupportTesting/Testable.php", +] +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.417271+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:8d2b65c7649f1f9fc1eed442cb668e44c527ed28b124a8978c2aa671dca74f76" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/livewire__livewire-10716/tests/capture.py b/tasks/livewire__livewire-10716/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/livewire__livewire-10716/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/livewire__livewire-10716/tests/instruction.md b/tasks/livewire__livewire-10716/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1a8a583b6a88543e909a2786cff905fcabed5a23 --- /dev/null +++ b/tasks/livewire__livewire-10716/tests/instruction.md @@ -0,0 +1,28 @@ +# Issue + +**Title:** [4.x] Preserve Livewire test types after response assertions + +## Description + +PHPStan reports `Call to an undefined method Illuminate\Testing\TestResponse::set()` for a valid Livewire test chain: + +```php +Livewire::test(Edit::class) + ->assertSuccessful() + ->set('foo', 'bar'); +``` + +Reported in https://github.com/livewire/livewire/discussions/6958 and reproduced on current 4.x with PHPStan 2.2.14. `Testable` mixes in Laravel's `TestResponse`, so its HTTP assertions inherit the response return type. At runtime, `Testable::__call()` forwards the assertion and returns the Livewire test instance instead. + +Adds three `@method $this` declarations for `assertSuccessful()`, `assertOk()`, and `assertStatus()` to describe that existing behavior. The component's generic type is retained after chaining. This addresses response-assertion chaining; the separate `actingAs()->test()` template-inference concern in the discussion is outside this patch. + +Validation: + +- A PHPStan level-8 fixture checks the original facade example, all three assertion-to-`set()` chains, and preservation of `Testable`. Five errors before the declarations, no errors afterward. No suppressions or casts. +- Existing testing/status-code suites plus a local runtime check: **63 tests passed, 245 assertions** on PHP 8.4.6 / Laravel 13.31.0. The runtime check verifies each assertion returns the identical `Testable` instance and the chain can still set a property. + +The patch changes only PHPDoc. The verification fixtures remain outside the package; no new test tooling or runtime code is introduced. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `de2bd6f28f58`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10716/tests/oracle.patch b/tasks/livewire__livewire-10716/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..42cb07bbdca128cd56584531d8ed25f12ff465f3 --- /dev/null +++ b/tasks/livewire__livewire-10716/tests/oracle.patch @@ -0,0 +1,15 @@ +diff --git a/src/Features/SupportTesting/Testable.php b/src/Features/SupportTesting/Testable.php +index fab583d6..e0dbc915 100644 +--- a/src/Features/SupportTesting/Testable.php ++++ b/src/Features/SupportTesting/Testable.php +@@ -13,6 +13,10 @@ use BackedEnum; + /** + * @template TComponent of \Livewire\Component + * ++ * @method $this assertSuccessful() ++ * @method $this assertOk() ++ * @method $this assertStatus(int $status) ++ * + * @mixin \Illuminate\Testing\TestResponse + */ + diff --git a/tasks/livewire__livewire-10716/tests/test.sh b/tasks/livewire__livewire-10716/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..5cd2cafba05d5df9616ae94f27296505aff428f3 --- /dev/null +++ b/tasks/livewire__livewire-10716/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace de2bd6f28f587ea2865c67f744b2a7b372c1ec4a > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/livewire__livewire-10716/tests/verifier.py b/tasks/livewire__livewire-10716/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/livewire__livewire-10716/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/livewire__livewire-10717/environment/Dockerfile b/tasks/livewire__livewire-10717/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..42451bf9810aa233dcbd3425d30e92180fbcaa4f --- /dev/null +++ b/tasks/livewire__livewire-10717/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/livewire/livewire.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/livewire/livewire.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/livewire/livewire.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 3bf965809bb5af9a0842cda1fb8a162b41ac9003 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 3bf965809bb5af9a0842cda1fb8a162b41ac9003 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 3bf965809bb5af9a0842cda1fb8a162b41ac9003 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/livewire__livewire-10717/instruction.md b/tasks/livewire__livewire-10717/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..001ee91e485b4692facf45a7edfa6159581b5654 --- /dev/null +++ b/tasks/livewire__livewire-10717/instruction.md @@ -0,0 +1,15 @@ +# Issue + +**Title:** [4.x] Prevent ReflectionException when resetting undeclared or dynamic properties + +## Description + +Right now calling $this->reset('someProp') or $this->reset('object.someProp') where the property isn't explicitly declared on the component/object throws an uncaught ReflectionException: Property Class::$someProp does not exist. + +InteractsWithProperties::reset() attempts (new \ReflectionProperty($freshInstance, (string) $property))->isInitialized($freshInstance) directly without checking if the property exists first. Form::reset() already checks property_exists() before reflecting, so this brings Component::reset() in line with that. + +With this check, undeclared or dynamic properties evaluate $isInitialized = false and get safely unset via data_forget() instead of crashing. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `3bf965809bb5`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10717/solution/patch.diff b/tasks/livewire__livewire-10717/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..4ab1170644f3edaa3d85afbca86179ea225d9595 --- /dev/null +++ b/tasks/livewire__livewire-10717/solution/patch.diff @@ -0,0 +1,89 @@ +diff --git a/src/Concerns/InteractsWithProperties.php b/src/Concerns/InteractsWithProperties.php +index cb19e46d..ef5cc204 100644 +--- a/src/Concerns/InteractsWithProperties.php ++++ b/src/Concerns/InteractsWithProperties.php +@@ -93,7 +93,8 @@ trait InteractsWithProperties + $object = data_get($freshInstance, $objectName, null); + + if (is_object($object)) { +- $isInitialized = (new \ReflectionProperty($object, (string) $propertyName))->isInitialized($object); ++ $isInitialized = property_exists($object, (string) $propertyName) ++ && (new \ReflectionProperty($object, (string) $propertyName))->isInitialized($object); + } elseif (is_array($object)) { + $isInitialized = Arr::has($freshInstance->{$objectName}, Utils::afterFirstDot((string) $property)); + } else { +@@ -108,7 +109,8 @@ trait InteractsWithProperties + continue; + } + +- $isInitialized = (new \ReflectionProperty($freshInstance, (string) $property))->isInitialized($freshInstance); ++ $isInitialized = property_exists($freshInstance, (string) $property) ++ && (new \ReflectionProperty($freshInstance, (string) $property))->isInitialized($freshInstance); + } + + // Handle resetting properties that are not initialized by default. +diff --git a/src/Concerns/Tests/ResetPropertiesUnitTest.php b/src/Concerns/Tests/ResetPropertiesUnitTest.php +index b72ca715..db15a8f6 100644 +--- a/src/Concerns/Tests/ResetPropertiesUnitTest.php ++++ b/src/Concerns/Tests/ResetPropertiesUnitTest.php +@@ -183,6 +183,32 @@ class ResetPropertiesUnitTest extends \Tests\TestCase + $this->assertEquals('baz', $component->pullResult['foo']); + $this->assertFalse(array_key_exists('bob', $component->pullResult)); + } ++ ++ public function test_can_reset_non_existent_property_without_throwing() ++ { ++ $component = Livewire::test(ResetPropertiesComponent::class) ++ ->call('resetKeys', 'nonExistent'); ++ ++ $this->assertFalse(isset($component->nonExistent)); ++ } ++ ++ public function test_can_reset_dynamic_property() ++ { ++ $component = Livewire::test(ResetPropertiesDynamicPropertyComponent::class) ++ ->call('setDynamic', 'dynamicProp', 'hello') ++ ->assertSetStrict('dynamicProp', 'hello') ++ ->call('resetKeys', 'dynamicProp'); ++ ++ $this->assertFalse(isset($component->dynamicProp)); ++ } ++ ++ public function test_can_reset_nested_non_existent_property_on_object() ++ { ++ $component = Livewire::test(ResetPropertiesComponentWithObject::class) ++ ->call('resetKeys', 'user.nonExistent'); ++ ++ $this->assertFalse(isset($component->user->nonExistent)); ++ } + } + + class ResetPropertiesComponent extends TestComponent +@@ -226,3 +252,27 @@ class ResetPropertiesComponent extends TestComponent + $this->pullResult = $this->pull(...$args); + } + } ++ ++#[\AllowDynamicProperties] ++class ResetPropertiesDynamicPropertyComponent extends ResetPropertiesComponent ++{ ++ public function setDynamic($key, $val) ++ { ++ $this->{$key} = $val; ++ } ++} ++ ++class ResetPropertiesComponentWithObject extends TestComponent ++{ ++ public $user; ++ ++ public function mount() ++ { ++ $this->user = new \stdClass; ++ } ++ ++ public function resetKeys($keys) ++ { ++ $this->reset($keys); ++ } ++} diff --git a/tasks/livewire__livewire-10717/solution/solve.sh b/tasks/livewire__livewire-10717/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/livewire__livewire-10717/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/livewire__livewire-10717/task.toml b/tasks/livewire__livewire-10717/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..8c6966a661c7a60be1a07b6aabf0d587f5443092 --- /dev/null +++ b/tasks/livewire__livewire-10717/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/livewire__livewire-10717" +description = "[4.x] Prevent ReflectionException when resetting undeclared or dynamic properties" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "livewire", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "livewire/livewire" +ref = "3bf965809bb5af9a0842cda1fb8a162b41ac9003" +reference = "https://github.com/livewire/livewire/pull/10717" +source_access = "auto" +built_at = "2026-11-16T16:09:51.465584+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:65fa79d87fbca4e6ec5434520047cdaeae1a9cde007f2890914ea0a749f95e29" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-21T12:56:17Z" +diff_format = "unified" +context_files = [ + "src/Concerns/InteractsWithProperties.php", + "src/Concerns/Tests/ResetPropertiesUnitTest.php", +] +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.417916+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:65c1b8420d092245064d9e01a30f8fcca28a246ff48793246c208ebec5b3b417" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/livewire__livewire-10717/tests/capture.py b/tasks/livewire__livewire-10717/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/livewire__livewire-10717/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/livewire__livewire-10717/tests/instruction.md b/tasks/livewire__livewire-10717/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..001ee91e485b4692facf45a7edfa6159581b5654 --- /dev/null +++ b/tasks/livewire__livewire-10717/tests/instruction.md @@ -0,0 +1,15 @@ +# Issue + +**Title:** [4.x] Prevent ReflectionException when resetting undeclared or dynamic properties + +## Description + +Right now calling $this->reset('someProp') or $this->reset('object.someProp') where the property isn't explicitly declared on the component/object throws an uncaught ReflectionException: Property Class::$someProp does not exist. + +InteractsWithProperties::reset() attempts (new \ReflectionProperty($freshInstance, (string) $property))->isInitialized($freshInstance) directly without checking if the property exists first. Form::reset() already checks property_exists() before reflecting, so this brings Component::reset() in line with that. + +With this check, undeclared or dynamic properties evaluate $isInitialized = false and get safely unset via data_forget() instead of crashing. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `3bf965809bb5`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10717/tests/oracle.patch b/tasks/livewire__livewire-10717/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..4ab1170644f3edaa3d85afbca86179ea225d9595 --- /dev/null +++ b/tasks/livewire__livewire-10717/tests/oracle.patch @@ -0,0 +1,89 @@ +diff --git a/src/Concerns/InteractsWithProperties.php b/src/Concerns/InteractsWithProperties.php +index cb19e46d..ef5cc204 100644 +--- a/src/Concerns/InteractsWithProperties.php ++++ b/src/Concerns/InteractsWithProperties.php +@@ -93,7 +93,8 @@ trait InteractsWithProperties + $object = data_get($freshInstance, $objectName, null); + + if (is_object($object)) { +- $isInitialized = (new \ReflectionProperty($object, (string) $propertyName))->isInitialized($object); ++ $isInitialized = property_exists($object, (string) $propertyName) ++ && (new \ReflectionProperty($object, (string) $propertyName))->isInitialized($object); + } elseif (is_array($object)) { + $isInitialized = Arr::has($freshInstance->{$objectName}, Utils::afterFirstDot((string) $property)); + } else { +@@ -108,7 +109,8 @@ trait InteractsWithProperties + continue; + } + +- $isInitialized = (new \ReflectionProperty($freshInstance, (string) $property))->isInitialized($freshInstance); ++ $isInitialized = property_exists($freshInstance, (string) $property) ++ && (new \ReflectionProperty($freshInstance, (string) $property))->isInitialized($freshInstance); + } + + // Handle resetting properties that are not initialized by default. +diff --git a/src/Concerns/Tests/ResetPropertiesUnitTest.php b/src/Concerns/Tests/ResetPropertiesUnitTest.php +index b72ca715..db15a8f6 100644 +--- a/src/Concerns/Tests/ResetPropertiesUnitTest.php ++++ b/src/Concerns/Tests/ResetPropertiesUnitTest.php +@@ -183,6 +183,32 @@ class ResetPropertiesUnitTest extends \Tests\TestCase + $this->assertEquals('baz', $component->pullResult['foo']); + $this->assertFalse(array_key_exists('bob', $component->pullResult)); + } ++ ++ public function test_can_reset_non_existent_property_without_throwing() ++ { ++ $component = Livewire::test(ResetPropertiesComponent::class) ++ ->call('resetKeys', 'nonExistent'); ++ ++ $this->assertFalse(isset($component->nonExistent)); ++ } ++ ++ public function test_can_reset_dynamic_property() ++ { ++ $component = Livewire::test(ResetPropertiesDynamicPropertyComponent::class) ++ ->call('setDynamic', 'dynamicProp', 'hello') ++ ->assertSetStrict('dynamicProp', 'hello') ++ ->call('resetKeys', 'dynamicProp'); ++ ++ $this->assertFalse(isset($component->dynamicProp)); ++ } ++ ++ public function test_can_reset_nested_non_existent_property_on_object() ++ { ++ $component = Livewire::test(ResetPropertiesComponentWithObject::class) ++ ->call('resetKeys', 'user.nonExistent'); ++ ++ $this->assertFalse(isset($component->user->nonExistent)); ++ } + } + + class ResetPropertiesComponent extends TestComponent +@@ -226,3 +252,27 @@ class ResetPropertiesComponent extends TestComponent + $this->pullResult = $this->pull(...$args); + } + } ++ ++#[\AllowDynamicProperties] ++class ResetPropertiesDynamicPropertyComponent extends ResetPropertiesComponent ++{ ++ public function setDynamic($key, $val) ++ { ++ $this->{$key} = $val; ++ } ++} ++ ++class ResetPropertiesComponentWithObject extends TestComponent ++{ ++ public $user; ++ ++ public function mount() ++ { ++ $this->user = new \stdClass; ++ } ++ ++ public function resetKeys($keys) ++ { ++ $this->reset($keys); ++ } ++} diff --git a/tasks/livewire__livewire-10717/tests/test.sh b/tasks/livewire__livewire-10717/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..44997c3f933c87434786b33595c4b04272dca7d6 --- /dev/null +++ b/tasks/livewire__livewire-10717/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 3bf965809bb5af9a0842cda1fb8a162b41ac9003 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/livewire__livewire-10717/tests/verifier.py b/tasks/livewire__livewire-10717/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/livewire__livewire-10717/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/livewire__livewire-10718/environment/Dockerfile b/tasks/livewire__livewire-10718/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..42451bf9810aa233dcbd3425d30e92180fbcaa4f --- /dev/null +++ b/tasks/livewire__livewire-10718/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/livewire/livewire.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/livewire/livewire.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/livewire/livewire.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 3bf965809bb5af9a0842cda1fb8a162b41ac9003 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 3bf965809bb5af9a0842cda1fb8a162b41ac9003 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 3bf965809bb5af9a0842cda1fb8a162b41ac9003 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/livewire__livewire-10718/instruction.md b/tasks/livewire__livewire-10718/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..814bd741e858d7f0f51fb25a24930c4ba2649b67 --- /dev/null +++ b/tasks/livewire__livewire-10718/instruction.md @@ -0,0 +1,48 @@ +# Issue + +**Title:** [4.x] Prevent DOMDocument ValueError in PHP 8.4+ and null body warning on empty markup + +## Description + +## The scenario + +With `app.debug` enabled, a component whose view contains only a ` +``` + +...or whose template has been entirely commented out: + +```blade + +``` + +## The problem + +Multiple root element detection only runs when `app.debug` is enabled, so these views render without error in production but crash in local development — a debugging aid shouldn't be the thing that throws. + +Both crash inside `SupportMultipleRootElementDetection::getRootElementCount()`: + +- **Script/style-only view:** the tags are stripped before parsing, leaving an empty string. On PHP 8.4+ `DOMDocument::loadHTML()` throws `ValueError: Argument #1 ($source) must not be empty` (earlier versions emit a warning, which Laravel converts to an `ErrorException`). +- **Commented-out template:** libxml doesn't create a `` for a document with no content, so `$body` is `null` and reading `$body->childNodes` raises `Attempt to read property "childNodes" on null`. + +## The solution + +Return `0` from `getRootElementCount()` in those two cases: when nothing is left to parse after stripping ` ++ HTML; ++ } ++ })->assertSuccessful(); ++ } ++ ++ function test_allow_style_tag_as_only_element() ++ { ++ config()->set('app.debug', true); ++ ++ Livewire::test(new class extends Component { ++ function render() ++ { ++ return <<<'HTML' ++ ++ HTML; ++ } ++ })->assertSuccessful(); ++ } ++ ++ function test_allow_entirely_commented_out_template() ++ { ++ config()->set('app.debug', true); ++ ++ // A document containing only a comment is parsed without a ... ++ Livewire::test(new class extends Component { ++ function render() ++ { ++ return <<<'HTML' ++ ++ HTML; ++ } ++ })->assertSuccessful(); ++ } ++ ++ function test_root_elements_are_counted() ++ { ++ $detector = new SupportMultipleRootElementDetection; ++ ++ $this->assertSame(1, $detector->getRootElementCount('
First element
')); ++ $this->assertSame(2, $detector->getRootElementCount('
First element
Second element
')); ++ $this->assertSame(1, $detector->getRootElementCount('
First element
')); ++ ++ // Markup that leaves no elements behind to count... ++ $this->assertSame(0, $detector->getRootElementCount('')); ++ $this->assertSame(0, $detector->getRootElementCount('')); ++ $this->assertSame(0, $detector->getRootElementCount("")); ++ } ++ + function test_dont_throw_error_in_production_so_that_there_is_no_perf_penalty() + { + config()->set('app.debug', false); diff --git a/tasks/livewire__livewire-10718/solution/solve.sh b/tasks/livewire__livewire-10718/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/livewire__livewire-10718/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/livewire__livewire-10718/task.toml b/tasks/livewire__livewire-10718/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..79686fa39f646a64714e95ca85845c927f52dd12 --- /dev/null +++ b/tasks/livewire__livewire-10718/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/livewire__livewire-10718" +description = "[4.x] Prevent DOMDocument ValueError in PHP 8.4+ and null body warning on empty markup" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "livewire", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "livewire/livewire" +ref = "3bf965809bb5af9a0842cda1fb8a162b41ac9003" +reference = "https://github.com/livewire/livewire/pull/10718" +source_access = "auto" +built_at = "2026-11-16T16:09:51.467927+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:4583239ceb8d5afc71d58c7440e00609a9cc4e696ea62fbbf37f83f433a23774" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-21T12:34:25Z" +diff_format = "unified" +context_files = [ + "src/Features/SupportMultipleRootElementDetection/SupportMultipleRootElementDetection.php", + "src/Features/SupportMultipleRootElementDetection/UnitTest.php", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 75 +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.418490+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:65c1b8420d092245064d9e01a30f8fcca28a246ff48793246c208ebec5b3b417" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/livewire__livewire-10718/tests/capture.py b/tasks/livewire__livewire-10718/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/livewire__livewire-10718/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/livewire__livewire-10718/tests/instruction.md b/tasks/livewire__livewire-10718/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..814bd741e858d7f0f51fb25a24930c4ba2649b67 --- /dev/null +++ b/tasks/livewire__livewire-10718/tests/instruction.md @@ -0,0 +1,48 @@ +# Issue + +**Title:** [4.x] Prevent DOMDocument ValueError in PHP 8.4+ and null body warning on empty markup + +## Description + +## The scenario + +With `app.debug` enabled, a component whose view contains only a ` +``` + +...or whose template has been entirely commented out: + +```blade + +``` + +## The problem + +Multiple root element detection only runs when `app.debug` is enabled, so these views render without error in production but crash in local development — a debugging aid shouldn't be the thing that throws. + +Both crash inside `SupportMultipleRootElementDetection::getRootElementCount()`: + +- **Script/style-only view:** the tags are stripped before parsing, leaving an empty string. On PHP 8.4+ `DOMDocument::loadHTML()` throws `ValueError: Argument #1 ($source) must not be empty` (earlier versions emit a warning, which Laravel converts to an `ErrorException`). +- **Commented-out template:** libxml doesn't create a `` for a document with no content, so `$body` is `null` and reading `$body->childNodes` raises `Attempt to read property "childNodes" on null`. + +## The solution + +Return `0` from `getRootElementCount()` in those two cases: when nothing is left to parse after stripping ` ++ HTML; ++ } ++ })->assertSuccessful(); ++ } ++ ++ function test_allow_style_tag_as_only_element() ++ { ++ config()->set('app.debug', true); ++ ++ Livewire::test(new class extends Component { ++ function render() ++ { ++ return <<<'HTML' ++ ++ HTML; ++ } ++ })->assertSuccessful(); ++ } ++ ++ function test_allow_entirely_commented_out_template() ++ { ++ config()->set('app.debug', true); ++ ++ // A document containing only a comment is parsed without a ... ++ Livewire::test(new class extends Component { ++ function render() ++ { ++ return <<<'HTML' ++ ++ HTML; ++ } ++ })->assertSuccessful(); ++ } ++ ++ function test_root_elements_are_counted() ++ { ++ $detector = new SupportMultipleRootElementDetection; ++ ++ $this->assertSame(1, $detector->getRootElementCount('
First element
')); ++ $this->assertSame(2, $detector->getRootElementCount('
First element
Second element
')); ++ $this->assertSame(1, $detector->getRootElementCount('
First element
')); ++ ++ // Markup that leaves no elements behind to count... ++ $this->assertSame(0, $detector->getRootElementCount('')); ++ $this->assertSame(0, $detector->getRootElementCount('')); ++ $this->assertSame(0, $detector->getRootElementCount("")); ++ } ++ + function test_dont_throw_error_in_production_so_that_there_is_no_perf_penalty() + { + config()->set('app.debug', false); diff --git a/tasks/livewire__livewire-10718/tests/test.sh b/tasks/livewire__livewire-10718/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..44997c3f933c87434786b33595c4b04272dca7d6 --- /dev/null +++ b/tasks/livewire__livewire-10718/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 3bf965809bb5af9a0842cda1fb8a162b41ac9003 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/livewire__livewire-10718/tests/verifier.py b/tasks/livewire__livewire-10718/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/livewire__livewire-10718/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/livewire__livewire-10719/environment/Dockerfile b/tasks/livewire__livewire-10719/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..59b1117670ac7343f73a9adf89f1d05fcf1a3884 --- /dev/null +++ b/tasks/livewire__livewire-10719/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/livewire/livewire.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/livewire/livewire.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/livewire/livewire.git +WORKDIR /workspace +RUN git fetch --depth 1 origin cfdf23c7936eeebe11fc4a7b0b3bddba7255fd31 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard cfdf23c7936eeebe11fc4a7b0b3bddba7255fd31 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base cfdf23c7936eeebe11fc4a7b0b3bddba7255fd31 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/livewire__livewire-10719/instruction.md b/tasks/livewire__livewire-10719/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3d2f75eced6bcc46eea624082abd698473605aba --- /dev/null +++ b/tasks/livewire__livewire-10719/instruction.md @@ -0,0 +1,26 @@ +# Issue + +**Title:** [4.x] Prefetch navigate hover links on keyboard focus + +## Description + +`wire:navigate.hover` currently gives mouse users a prefetch head start, but tabbing to the same link does not fetch anything until Enter is pressed. Discussion #10353 asks for the same behavior on keyboard focus. + +This adds focus/blur alongside mouseenter/mouseleave to the existing delayed-prefetch helper. Focusing the link for 60 ms starts a prefetch; tabbing away sooner cancels it. Hover and focus each cancel their own timer, and the existing URL cache prevents duplicate requests when both occur. The common native-link and same-page-fragment checks still apply. + +Source: https://github.com/livewire/livewire/discussions/10353 + +Verified before and after in a separate Laravel app: click a Start button, press Tab onto a `wire:navigate.hover` link, and observe the destination request counter without navigating. Before: zero requests. After: one request; Enter opens the destination. No console errors. + +The new real-keyboard browser test failed before the change with “Livewire navigate prefetch request was never triggered.” After rebuilding assets, **10 focused browser tests pass, 37 assertions**, including keyboard focus, rapid Tab cancellation, focus/hover cache reuse, Enter navigation, the existing 30-second hover cache, failed prefetch behavior, native links, and same-page fragments. + +```sh +npm run build +vendor/bin/phpunit src/Features/SupportNavigate/BrowserTest.php src/Features/SupportNavigate/FragmentBrowserTest.php --filter='prefetch|test_navigate_falls_back_to_browser_for_native_links|test_same_page_fragment_links_do_not_fetch_or_swap_the_page|test_fragment_links_support_keyboard_activation_and_repeated_clicks' +``` + +Updates both navigation documentation pages to describe focus prefetching. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `cfdf23c7936e`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10719/solution/patch.diff b/tasks/livewire__livewire-10719/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..0832d700cf10c1a3935096d7bdb89c935e8697c0 --- /dev/null +++ b/tasks/livewire__livewire-10719/solution/patch.diff @@ -0,0 +1,131 @@ +diff --git a/docs/navigate.md b/docs/navigate.md +index 3377aa4d..6e08894d 100644 +--- a/docs/navigate.md ++++ b/docs/navigate.md +@@ -67,10 +67,10 @@ If you want an even more aggressive approach to prefetching, you may use the `.h + Posts + ``` + +-The `.hover` modifier will instruct Livewire to prefetch the page after a user has hovered over the link for `60` milliseconds. ++The `.hover` modifier will instruct Livewire to prefetch the page after a user has hovered over or focused the link for `60` milliseconds. This also gives keyboard users a head start when they tab to a link. Moving focus away before the delay elapses cancels the pending focus prefetch. + + > [!warning] Prefetching on hover increases server usage +-> Because not all users will click a link they hover over, adding `.hover` will request pages that may not be needed, though Livewire attempts to mitigate some of this overhead by waiting `60` milliseconds before prefetching the page. ++> Because not all users will follow a link they hover over or focus, adding `.hover` will request pages that may not be needed, though Livewire attempts to mitigate some of this overhead by waiting `60` milliseconds before prefetching the page. + + ## Persisting elements across page visits + +diff --git a/docs/wire-navigate.md b/docs/wire-navigate.md +index 924f31dd..3bbe88cc 100644 +--- a/docs/wire-navigate.md ++++ b/docs/wire-navigate.md +@@ -33,7 +33,7 @@ The `data-current` attribute is added and removed automatically as users navigat + + ## Prefetching pages on hover + +-By adding the `.hover` modifier, Livewire will pre-fetch a page when a user hovers over a link. This way, the page will have already been downloaded from the server when the user clicks on the link. ++By adding the `.hover` modifier, Livewire will pre-fetch a page after a user hovers over or focuses a link for 60 milliseconds. This gives both mouse and keyboard users a head start before following the link. + + ```blade + Dashboard +@@ -59,4 +59,4 @@ wire:navigate + + | Modifier | Description | + |----------|-------------| +-| `.hover` | Prefetches the page when user hovers over the link | ++| `.hover` | Prefetches the page when the user hovers over or focuses the link | +diff --git a/js/plugins/navigate/index.js b/js/plugins/navigate/index.js +index 7ed9cfd5..18f128fb 100644 +--- a/js/plugins/navigate/index.js ++++ b/js/plugins/navigate/index.js +@@ -1,6 +1,6 @@ + import { pushUrl, replaceUrl, updateCurrentPageHtmlInHistoryStateForLaterBackButtonClicks, updateCurrentPageHtmlInSnapshotCacheForLaterBackButtonClicks, updateUrlAndStoreLatestHtmlForFutureBackButtons, whenTheBackOrForwardButtonIsClicked } from "./history" + import { getPretchedHtmlOr, prefetchHtml, storeThePrefetchedHtmlForWhenALinkIsClicked } from "./prefetch" +-import { createUrlObjectFromString, extractDestinationFromLink, isSameOrigin, isSamePageFragment, linkShouldBeHandledNatively, visitNatively, whenThisLinkIsHoveredFor, whenThisLinkIsPressed } from "./links" ++import { createUrlObjectFromString, extractDestinationFromLink, isSameOrigin, isSamePageFragment, linkShouldBeHandledNatively, visitNatively, whenThisLinkIsHoveredOrFocusedFor, whenThisLinkIsPressed } from "./links" + import { isTeleportTarget, packUpPersistedTeleports, removeAnyLeftOverStaleTeleportTargets, unPackPersistedTeleports } from "./teleport" + import { restoreScrollPositionOrScrollToTop, storeScrollInformationInHtmlBeforeNavigatingAway } from "./scroll" + import { isPersistedElement, putPersistantElementsBack, storePersistantElementsForLater } from "./persist" +@@ -47,7 +47,7 @@ export default function (Alpine) { + + let preserveScroll = modifiers.includes('preserve-scroll') + +- shouldPrefetchOnHover && whenThisLinkIsHoveredFor(el, 60, () => { ++ shouldPrefetchOnHover && whenThisLinkIsHoveredOrFocusedFor(el, 60, () => { + let destination = extractDestinationFromLink(el) + + if (linkShouldBeHandledNatively(el, destination) || isSamePageFragment(destination)) return +diff --git a/js/plugins/navigate/links.js b/js/plugins/navigate/links.js +index 7048ade6..58a5c98a 100644 +--- a/js/plugins/navigate/links.js ++++ b/js/plugins/navigate/links.js +@@ -60,19 +60,21 @@ export function whenThisLinkIsPressed(el, callback) { + }) + } + +-export function whenThisLinkIsHoveredFor(el, ms = 60, callback) { +- el.addEventListener('mouseenter', e => { +- let timeout = setTimeout(() => { +- callback(e) +- }, ms) +- +- let handler = () => { +- clearTimeout(timeout) +- el.removeEventListener('mouseleave', handler) +- } ++export function whenThisLinkIsHoveredOrFocusedFor(el, ms = 60, callback) { ++ for (let [enterEvent, leaveEvent] of [['mouseenter', 'mouseleave'], ['focus', 'blur']]) { ++ el.addEventListener(enterEvent, e => { ++ let timeout = setTimeout(() => { ++ callback(e) ++ }, ms) ++ ++ let handler = () => { ++ clearTimeout(timeout) ++ el.removeEventListener(leaveEvent, handler) ++ } + +- el.addEventListener('mouseleave', handler) +- }) ++ el.addEventListener(leaveEvent, handler) ++ }) ++ } + } + + export function extractDestinationFromLink(linkEl) { +diff --git a/src/Features/SupportNavigate/BrowserTest.php b/src/Features/SupportNavigate/BrowserTest.php +index ca43f6bb..1a062ef2 100644 +--- a/src/Features/SupportNavigate/BrowserTest.php ++++ b/src/Features/SupportNavigate/BrowserTest.php +@@ -1679,6 +1679,31 @@ class BrowserTest extends \Tests\BrowserTestCase + }); + } + ++ public function test_navigate_hover_prefetches_when_a_link_is_focused_using_the_keyboard() ++ { ++ $this->browse(function ($browser) { ++ $browser ++ ->visit('/first') ++ ->waitForNavigatePrefetchRequest()->keys('@link.to.tel', '{tab}') ++ ->assertFocused('@link.to.second') ++ ->assertPathIs('/first') ++ ->waitForNoNavigatePrefetchRequest()->mouseover('@link.to.second') ++ ->waitForNavigate()->keys('@link.to.second', '{enter}') ++ ->assertSee('On second'); ++ }); ++ } ++ ++ public function test_navigate_hover_does_not_prefetch_when_quickly_tabbing_past_links() ++ { ++ $this->browse(function ($browser) { ++ $browser ++ ->visit('/first') ++ ->waitForNoNavigatePrefetchRequest()->keys('@link.to.tel', '{tab}', '{tab}', '{tab}', '{tab}') ++ ->assertFocused('@redirect.to.second') ++ ->assertPathIs('/first'); ++ }); ++ } ++ + public function test_navigate_hover_prefetches_and_caches_for_a_default_30_seconds() + { + $this->browse(function ($browser) { diff --git a/tasks/livewire__livewire-10719/solution/solve.sh b/tasks/livewire__livewire-10719/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/livewire__livewire-10719/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/livewire__livewire-10719/task.toml b/tasks/livewire__livewire-10719/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..923d5511037dcda8625fda27364f7ed8b97449c0 --- /dev/null +++ b/tasks/livewire__livewire-10719/task.toml @@ -0,0 +1,72 @@ +version = "1.0" + +[task] +name = "trending/livewire__livewire-10719" +description = "[4.x] Prefetch navigate hover links on keyboard focus" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "livewire", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "livewire/livewire" +ref = "cfdf23c7936eeebe11fc4a7b0b3bddba7255fd31" +reference = "https://github.com/livewire/livewire/pull/10719" +source_access = "auto" +built_at = "2026-11-16T16:09:51.474161+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:9f0d2661e043147fe6dd3c45e6661a6d71b03fbae42e1bfdd7849f5ccb2eba45" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-16T19:43:13Z" +diff_format = "unified" +context_files = [ + "docs/navigate.md", + "docs/wire-navigate.md", + "js/plugins/navigate/index.js", + "js/plugins/navigate/links.js", + "src/Features/SupportNavigate/BrowserTest.php", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 63 +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.419041+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:4acbc917bcef4c5aa53cb68f423ac9761b0654fcd67bcc8269ea4d3a9c40c987" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/livewire__livewire-10719/tests/capture.py b/tasks/livewire__livewire-10719/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/livewire__livewire-10719/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/livewire__livewire-10719/tests/instruction.md b/tasks/livewire__livewire-10719/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3d2f75eced6bcc46eea624082abd698473605aba --- /dev/null +++ b/tasks/livewire__livewire-10719/tests/instruction.md @@ -0,0 +1,26 @@ +# Issue + +**Title:** [4.x] Prefetch navigate hover links on keyboard focus + +## Description + +`wire:navigate.hover` currently gives mouse users a prefetch head start, but tabbing to the same link does not fetch anything until Enter is pressed. Discussion #10353 asks for the same behavior on keyboard focus. + +This adds focus/blur alongside mouseenter/mouseleave to the existing delayed-prefetch helper. Focusing the link for 60 ms starts a prefetch; tabbing away sooner cancels it. Hover and focus each cancel their own timer, and the existing URL cache prevents duplicate requests when both occur. The common native-link and same-page-fragment checks still apply. + +Source: https://github.com/livewire/livewire/discussions/10353 + +Verified before and after in a separate Laravel app: click a Start button, press Tab onto a `wire:navigate.hover` link, and observe the destination request counter without navigating. Before: zero requests. After: one request; Enter opens the destination. No console errors. + +The new real-keyboard browser test failed before the change with “Livewire navigate prefetch request was never triggered.” After rebuilding assets, **10 focused browser tests pass, 37 assertions**, including keyboard focus, rapid Tab cancellation, focus/hover cache reuse, Enter navigation, the existing 30-second hover cache, failed prefetch behavior, native links, and same-page fragments. + +```sh +npm run build +vendor/bin/phpunit src/Features/SupportNavigate/BrowserTest.php src/Features/SupportNavigate/FragmentBrowserTest.php --filter='prefetch|test_navigate_falls_back_to_browser_for_native_links|test_same_page_fragment_links_do_not_fetch_or_swap_the_page|test_fragment_links_support_keyboard_activation_and_repeated_clicks' +``` + +Updates both navigation documentation pages to describe focus prefetching. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `cfdf23c7936e`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10719/tests/oracle.patch b/tasks/livewire__livewire-10719/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..0832d700cf10c1a3935096d7bdb89c935e8697c0 --- /dev/null +++ b/tasks/livewire__livewire-10719/tests/oracle.patch @@ -0,0 +1,131 @@ +diff --git a/docs/navigate.md b/docs/navigate.md +index 3377aa4d..6e08894d 100644 +--- a/docs/navigate.md ++++ b/docs/navigate.md +@@ -67,10 +67,10 @@ If you want an even more aggressive approach to prefetching, you may use the `.h + Posts + ``` + +-The `.hover` modifier will instruct Livewire to prefetch the page after a user has hovered over the link for `60` milliseconds. ++The `.hover` modifier will instruct Livewire to prefetch the page after a user has hovered over or focused the link for `60` milliseconds. This also gives keyboard users a head start when they tab to a link. Moving focus away before the delay elapses cancels the pending focus prefetch. + + > [!warning] Prefetching on hover increases server usage +-> Because not all users will click a link they hover over, adding `.hover` will request pages that may not be needed, though Livewire attempts to mitigate some of this overhead by waiting `60` milliseconds before prefetching the page. ++> Because not all users will follow a link they hover over or focus, adding `.hover` will request pages that may not be needed, though Livewire attempts to mitigate some of this overhead by waiting `60` milliseconds before prefetching the page. + + ## Persisting elements across page visits + +diff --git a/docs/wire-navigate.md b/docs/wire-navigate.md +index 924f31dd..3bbe88cc 100644 +--- a/docs/wire-navigate.md ++++ b/docs/wire-navigate.md +@@ -33,7 +33,7 @@ The `data-current` attribute is added and removed automatically as users navigat + + ## Prefetching pages on hover + +-By adding the `.hover` modifier, Livewire will pre-fetch a page when a user hovers over a link. This way, the page will have already been downloaded from the server when the user clicks on the link. ++By adding the `.hover` modifier, Livewire will pre-fetch a page after a user hovers over or focuses a link for 60 milliseconds. This gives both mouse and keyboard users a head start before following the link. + + ```blade + Dashboard +@@ -59,4 +59,4 @@ wire:navigate + + | Modifier | Description | + |----------|-------------| +-| `.hover` | Prefetches the page when user hovers over the link | ++| `.hover` | Prefetches the page when the user hovers over or focuses the link | +diff --git a/js/plugins/navigate/index.js b/js/plugins/navigate/index.js +index 7ed9cfd5..18f128fb 100644 +--- a/js/plugins/navigate/index.js ++++ b/js/plugins/navigate/index.js +@@ -1,6 +1,6 @@ + import { pushUrl, replaceUrl, updateCurrentPageHtmlInHistoryStateForLaterBackButtonClicks, updateCurrentPageHtmlInSnapshotCacheForLaterBackButtonClicks, updateUrlAndStoreLatestHtmlForFutureBackButtons, whenTheBackOrForwardButtonIsClicked } from "./history" + import { getPretchedHtmlOr, prefetchHtml, storeThePrefetchedHtmlForWhenALinkIsClicked } from "./prefetch" +-import { createUrlObjectFromString, extractDestinationFromLink, isSameOrigin, isSamePageFragment, linkShouldBeHandledNatively, visitNatively, whenThisLinkIsHoveredFor, whenThisLinkIsPressed } from "./links" ++import { createUrlObjectFromString, extractDestinationFromLink, isSameOrigin, isSamePageFragment, linkShouldBeHandledNatively, visitNatively, whenThisLinkIsHoveredOrFocusedFor, whenThisLinkIsPressed } from "./links" + import { isTeleportTarget, packUpPersistedTeleports, removeAnyLeftOverStaleTeleportTargets, unPackPersistedTeleports } from "./teleport" + import { restoreScrollPositionOrScrollToTop, storeScrollInformationInHtmlBeforeNavigatingAway } from "./scroll" + import { isPersistedElement, putPersistantElementsBack, storePersistantElementsForLater } from "./persist" +@@ -47,7 +47,7 @@ export default function (Alpine) { + + let preserveScroll = modifiers.includes('preserve-scroll') + +- shouldPrefetchOnHover && whenThisLinkIsHoveredFor(el, 60, () => { ++ shouldPrefetchOnHover && whenThisLinkIsHoveredOrFocusedFor(el, 60, () => { + let destination = extractDestinationFromLink(el) + + if (linkShouldBeHandledNatively(el, destination) || isSamePageFragment(destination)) return +diff --git a/js/plugins/navigate/links.js b/js/plugins/navigate/links.js +index 7048ade6..58a5c98a 100644 +--- a/js/plugins/navigate/links.js ++++ b/js/plugins/navigate/links.js +@@ -60,19 +60,21 @@ export function whenThisLinkIsPressed(el, callback) { + }) + } + +-export function whenThisLinkIsHoveredFor(el, ms = 60, callback) { +- el.addEventListener('mouseenter', e => { +- let timeout = setTimeout(() => { +- callback(e) +- }, ms) +- +- let handler = () => { +- clearTimeout(timeout) +- el.removeEventListener('mouseleave', handler) +- } ++export function whenThisLinkIsHoveredOrFocusedFor(el, ms = 60, callback) { ++ for (let [enterEvent, leaveEvent] of [['mouseenter', 'mouseleave'], ['focus', 'blur']]) { ++ el.addEventListener(enterEvent, e => { ++ let timeout = setTimeout(() => { ++ callback(e) ++ }, ms) ++ ++ let handler = () => { ++ clearTimeout(timeout) ++ el.removeEventListener(leaveEvent, handler) ++ } + +- el.addEventListener('mouseleave', handler) +- }) ++ el.addEventListener(leaveEvent, handler) ++ }) ++ } + } + + export function extractDestinationFromLink(linkEl) { +diff --git a/src/Features/SupportNavigate/BrowserTest.php b/src/Features/SupportNavigate/BrowserTest.php +index ca43f6bb..1a062ef2 100644 +--- a/src/Features/SupportNavigate/BrowserTest.php ++++ b/src/Features/SupportNavigate/BrowserTest.php +@@ -1679,6 +1679,31 @@ class BrowserTest extends \Tests\BrowserTestCase + }); + } + ++ public function test_navigate_hover_prefetches_when_a_link_is_focused_using_the_keyboard() ++ { ++ $this->browse(function ($browser) { ++ $browser ++ ->visit('/first') ++ ->waitForNavigatePrefetchRequest()->keys('@link.to.tel', '{tab}') ++ ->assertFocused('@link.to.second') ++ ->assertPathIs('/first') ++ ->waitForNoNavigatePrefetchRequest()->mouseover('@link.to.second') ++ ->waitForNavigate()->keys('@link.to.second', '{enter}') ++ ->assertSee('On second'); ++ }); ++ } ++ ++ public function test_navigate_hover_does_not_prefetch_when_quickly_tabbing_past_links() ++ { ++ $this->browse(function ($browser) { ++ $browser ++ ->visit('/first') ++ ->waitForNoNavigatePrefetchRequest()->keys('@link.to.tel', '{tab}', '{tab}', '{tab}', '{tab}') ++ ->assertFocused('@redirect.to.second') ++ ->assertPathIs('/first'); ++ }); ++ } ++ + public function test_navigate_hover_prefetches_and_caches_for_a_default_30_seconds() + { + $this->browse(function ($browser) { diff --git a/tasks/livewire__livewire-10719/tests/test.sh b/tasks/livewire__livewire-10719/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..8fa0def41393196c9ebd93c33b4c5a7e96706cdc --- /dev/null +++ b/tasks/livewire__livewire-10719/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace cfdf23c7936eeebe11fc4a7b0b3bddba7255fd31 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/livewire__livewire-10719/tests/verifier.py b/tasks/livewire__livewire-10719/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/livewire__livewire-10719/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/livewire__livewire-10720/environment/Dockerfile b/tasks/livewire__livewire-10720/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..bec439965816e7702501b7044dbfc39776775a4d --- /dev/null +++ b/tasks/livewire__livewire-10720/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/livewire/livewire.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/livewire/livewire.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/livewire/livewire.git +WORKDIR /workspace +RUN git fetch --depth 1 origin d34ce4e8db9779f449783cd0aebb7a7e73a800f5 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard d34ce4e8db9779f449783cd0aebb7a7e73a800f5 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base d34ce4e8db9779f449783cd0aebb7a7e73a800f5 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/livewire__livewire-10720/instruction.md b/tasks/livewire__livewire-10720/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5b08d2b47040f5bc934d2e6ccc80fdd2272ea361 --- /dev/null +++ b/tasks/livewire__livewire-10720/instruction.md @@ -0,0 +1,29 @@ +# Issue + +**Title:** [4.x] Allow missing model status assertions in component tests + +## Description + +An action that calls Eloquent's `findOrFail()` for a missing model returns a 404 in the application, but the equivalent Livewire test throws `ModelNotFoundException` before it can reach `assertNotFound()`: + +```php +Livewire::test(Users::class) + ->call('showFullDetails', 0) + ->assertNotFound(); +``` + +Reported in https://github.com/livewire/livewire/discussions/9447 and reproduced on current 4.x using an actual Eloquent collection's `findOrFail()`. + +Adds `ModelNotFoundException` to the test request broker's existing exception-handling allowlist. Laravel's normal handler can then convert it to a 404, just as it already does for authorization and HTTP exceptions. Explicit `withoutExceptionHandling()` still rethrows the exception. Application request handling is unchanged. + +Validation: the new 404 regression failed before the change and passes afterward. **64 tests passed, 237 assertions** on PHP 8.4.6 / Laravel 13.31.0: + +```sh +vendor/bin/phpunit src/Features/SupportTesting/Tests/TestableLivewireCanAssertStatusCodesUnitTest.php src/Features/SupportTesting/UnitTest.php +``` + +Coverage includes explicit exception-handling opt-out, existing 401/403/404 assertions, unexpected action errors propagating, and restoration of the application's exception handler and middleware state. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d34ce4e8db97`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10720/solution/patch.diff b/tasks/livewire__livewire-10720/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..5b1d8011305a749ca8181bd5a1fe15f70b507b55 --- /dev/null +++ b/tasks/livewire__livewire-10720/solution/patch.diff @@ -0,0 +1,66 @@ +diff --git a/src/Features/SupportTesting/RequestBroker.php b/src/Features/SupportTesting/RequestBroker.php +index 2673e21d..b127d8a6 100644 +--- a/src/Features/SupportTesting/RequestBroker.php ++++ b/src/Features/SupportTesting/RequestBroker.php +@@ -6,6 +6,7 @@ use Illuminate\Foundation\Testing\Concerns\InteractsWithExceptionHandling; + use Illuminate\Foundation\Testing\Concerns\MakesHttpRequests; + use Symfony\Component\HttpKernel\Exception\HttpException; + use Illuminate\Auth\Access\AuthorizationException; ++use Illuminate\Database\Eloquent\ModelNotFoundException; + use Illuminate\Contracts\Debug\ExceptionHandler; + use Livewire\Mechanisms\HandleRequests\HandleRequests; + +@@ -26,7 +27,7 @@ class RequestBroker + + $cachedShouldSkipMiddleware = $this->app->shouldSkipMiddleware(); + +- $this->withoutExceptionHandling([HttpException::class, AuthorizationException::class])->withoutMiddleware(); ++ $this->withoutExceptionHandling([HttpException::class, AuthorizationException::class, ModelNotFoundException::class])->withoutMiddleware(); + + try { + return app(HandleRequests::class)->temporarilyPropagateExceptions( +diff --git a/src/Features/SupportTesting/Tests/TestableLivewireCanAssertStatusCodesUnitTest.php b/src/Features/SupportTesting/Tests/TestableLivewireCanAssertStatusCodesUnitTest.php +index a67d321f..30f5eddc 100644 +--- a/src/Features/SupportTesting/Tests/TestableLivewireCanAssertStatusCodesUnitTest.php ++++ b/src/Features/SupportTesting/Tests/TestableLivewireCanAssertStatusCodesUnitTest.php +@@ -3,6 +3,8 @@ + namespace Livewire\Features\SupportTesting\Tests; + + use Symfony\Component\HttpKernel\Exception\HttpException; ++use Illuminate\Database\Eloquent\ModelNotFoundException; ++use Illuminate\Database\Eloquent\Collection; + use Livewire\Component; + use Livewire\Livewire; + use Tests\TestComponent; +@@ -57,6 +59,31 @@ class TestableLivewireCanAssertStatusCodesUnitTest extends \Tests\TestCase + ->assertSee('Hello!') + ->assertSeeHtml(''); + } ++ ++ function test_can_assert_not_found_when_an_action_cannot_find_a_model() ++ { ++ Livewire::test(MissingModelComponent::class) ++ ->call('showFullDetails', 0) ++ ->assertNotFound(); ++ } ++ ++ function test_missing_model_exceptions_are_rethrown_when_exception_handling_is_disabled() ++ { ++ $this->withoutExceptionHandling(); ++ ++ $this->expectException(ModelNotFoundException::class); ++ ++ Livewire::test(MissingModelComponent::class) ++ ->call('showFullDetails', 0); ++ } ++} ++ ++class MissingModelComponent extends TestComponent ++{ ++ public function showFullDetails($id) ++ { ++ (new Collection)->findOrFail($id); ++ } + } + + class NotFoundComponent extends Component diff --git a/tasks/livewire__livewire-10720/solution/solve.sh b/tasks/livewire__livewire-10720/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/livewire__livewire-10720/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/livewire__livewire-10720/task.toml b/tasks/livewire__livewire-10720/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..d30e39c3df0b7640434ee532202ead1f8ebed26c --- /dev/null +++ b/tasks/livewire__livewire-10720/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/livewire__livewire-10720" +description = "[4.x] Allow missing model status assertions in component tests" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "livewire", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "livewire/livewire" +ref = "d34ce4e8db9779f449783cd0aebb7a7e73a800f5" +reference = "https://github.com/livewire/livewire/pull/10720" +source_access = "auto" +built_at = "2026-11-16T16:09:51.472601+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:6ace6e95a7156f7c6bcb5bc8b504e878749e8aa4a9d46bfc36bd821fee4078e9" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-16T20:47:42Z" +diff_format = "unified" +context_files = [ + "src/Features/SupportTesting/RequestBroker.php", + "src/Features/SupportTesting/Tests/TestableLivewireCanAssertStatusCodesUnitTest.php", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 30 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.419570+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:b51b11e7fadfb5d2dd2bed16aaf2a60ebdca7d6a65f71c65c6ad636b5779f8f2" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/livewire__livewire-10720/tests/capture.py b/tasks/livewire__livewire-10720/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/livewire__livewire-10720/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/livewire__livewire-10720/tests/instruction.md b/tasks/livewire__livewire-10720/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5b08d2b47040f5bc934d2e6ccc80fdd2272ea361 --- /dev/null +++ b/tasks/livewire__livewire-10720/tests/instruction.md @@ -0,0 +1,29 @@ +# Issue + +**Title:** [4.x] Allow missing model status assertions in component tests + +## Description + +An action that calls Eloquent's `findOrFail()` for a missing model returns a 404 in the application, but the equivalent Livewire test throws `ModelNotFoundException` before it can reach `assertNotFound()`: + +```php +Livewire::test(Users::class) + ->call('showFullDetails', 0) + ->assertNotFound(); +``` + +Reported in https://github.com/livewire/livewire/discussions/9447 and reproduced on current 4.x using an actual Eloquent collection's `findOrFail()`. + +Adds `ModelNotFoundException` to the test request broker's existing exception-handling allowlist. Laravel's normal handler can then convert it to a 404, just as it already does for authorization and HTTP exceptions. Explicit `withoutExceptionHandling()` still rethrows the exception. Application request handling is unchanged. + +Validation: the new 404 regression failed before the change and passes afterward. **64 tests passed, 237 assertions** on PHP 8.4.6 / Laravel 13.31.0: + +```sh +vendor/bin/phpunit src/Features/SupportTesting/Tests/TestableLivewireCanAssertStatusCodesUnitTest.php src/Features/SupportTesting/UnitTest.php +``` + +Coverage includes explicit exception-handling opt-out, existing 401/403/404 assertions, unexpected action errors propagating, and restoration of the application's exception handler and middleware state. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d34ce4e8db97`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10720/tests/oracle.patch b/tasks/livewire__livewire-10720/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..5b1d8011305a749ca8181bd5a1fe15f70b507b55 --- /dev/null +++ b/tasks/livewire__livewire-10720/tests/oracle.patch @@ -0,0 +1,66 @@ +diff --git a/src/Features/SupportTesting/RequestBroker.php b/src/Features/SupportTesting/RequestBroker.php +index 2673e21d..b127d8a6 100644 +--- a/src/Features/SupportTesting/RequestBroker.php ++++ b/src/Features/SupportTesting/RequestBroker.php +@@ -6,6 +6,7 @@ use Illuminate\Foundation\Testing\Concerns\InteractsWithExceptionHandling; + use Illuminate\Foundation\Testing\Concerns\MakesHttpRequests; + use Symfony\Component\HttpKernel\Exception\HttpException; + use Illuminate\Auth\Access\AuthorizationException; ++use Illuminate\Database\Eloquent\ModelNotFoundException; + use Illuminate\Contracts\Debug\ExceptionHandler; + use Livewire\Mechanisms\HandleRequests\HandleRequests; + +@@ -26,7 +27,7 @@ class RequestBroker + + $cachedShouldSkipMiddleware = $this->app->shouldSkipMiddleware(); + +- $this->withoutExceptionHandling([HttpException::class, AuthorizationException::class])->withoutMiddleware(); ++ $this->withoutExceptionHandling([HttpException::class, AuthorizationException::class, ModelNotFoundException::class])->withoutMiddleware(); + + try { + return app(HandleRequests::class)->temporarilyPropagateExceptions( +diff --git a/src/Features/SupportTesting/Tests/TestableLivewireCanAssertStatusCodesUnitTest.php b/src/Features/SupportTesting/Tests/TestableLivewireCanAssertStatusCodesUnitTest.php +index a67d321f..30f5eddc 100644 +--- a/src/Features/SupportTesting/Tests/TestableLivewireCanAssertStatusCodesUnitTest.php ++++ b/src/Features/SupportTesting/Tests/TestableLivewireCanAssertStatusCodesUnitTest.php +@@ -3,6 +3,8 @@ + namespace Livewire\Features\SupportTesting\Tests; + + use Symfony\Component\HttpKernel\Exception\HttpException; ++use Illuminate\Database\Eloquent\ModelNotFoundException; ++use Illuminate\Database\Eloquent\Collection; + use Livewire\Component; + use Livewire\Livewire; + use Tests\TestComponent; +@@ -57,6 +59,31 @@ class TestableLivewireCanAssertStatusCodesUnitTest extends \Tests\TestCase + ->assertSee('Hello!') + ->assertSeeHtml(''); + } ++ ++ function test_can_assert_not_found_when_an_action_cannot_find_a_model() ++ { ++ Livewire::test(MissingModelComponent::class) ++ ->call('showFullDetails', 0) ++ ->assertNotFound(); ++ } ++ ++ function test_missing_model_exceptions_are_rethrown_when_exception_handling_is_disabled() ++ { ++ $this->withoutExceptionHandling(); ++ ++ $this->expectException(ModelNotFoundException::class); ++ ++ Livewire::test(MissingModelComponent::class) ++ ->call('showFullDetails', 0); ++ } ++} ++ ++class MissingModelComponent extends TestComponent ++{ ++ public function showFullDetails($id) ++ { ++ (new Collection)->findOrFail($id); ++ } + } + + class NotFoundComponent extends Component diff --git a/tasks/livewire__livewire-10720/tests/test.sh b/tasks/livewire__livewire-10720/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..d1671c312213b6903aefd1c0d0aae28ded0f009e --- /dev/null +++ b/tasks/livewire__livewire-10720/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace d34ce4e8db9779f449783cd0aebb7a7e73a800f5 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/livewire__livewire-10720/tests/verifier.py b/tasks/livewire__livewire-10720/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/livewire__livewire-10720/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/livewire__livewire-10721/environment/Dockerfile b/tasks/livewire__livewire-10721/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..42451bf9810aa233dcbd3425d30e92180fbcaa4f --- /dev/null +++ b/tasks/livewire__livewire-10721/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/livewire/livewire.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/livewire/livewire.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/livewire/livewire.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 3bf965809bb5af9a0842cda1fb8a162b41ac9003 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 3bf965809bb5af9a0842cda1fb8a162b41ac9003 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 3bf965809bb5af9a0842cda1fb8a162b41ac9003 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/livewire__livewire-10721/instruction.md b/tasks/livewire__livewire-10721/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8b05ce3acc037bc724e1595e103b299219c285df --- /dev/null +++ b/tasks/livewire__livewire-10721/instruction.md @@ -0,0 +1,29 @@ +# Issue + +**Title:** [4.x] Memoize computed properties that return null within a request + +## Description + +Hi! + +I got bit by this in one of our apps, and then saw that it was actually affecting several other apps too. + +I think the fix is simple and safe, it was talked about [here](https://github.com/livewire/livewire/discussions/3164) and a similar fix was implemented . + +--- + +A `#[Computed]` property that returns `null` is never memoized. Its body re-runs on every read within the same request. Non-null values memoize fine. + +The per-request memo in `BaseComputed::handleMagicGet()` is stored with `??=`: + +```php +$returnValue( + $this->requestCachedValue ??= $this->evaluateComputed() +); +``` + +`??=` only assigns when the left side is null, so an honest `null` result (an `->first()` that finds nothing, an optional relation, a "current item" lookup with no match) looks the same as "not evaluated yet". Reading `$this->foo` four times in one request evaluates `foo()` four times. With this change it's once. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `3bf965809bb5`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10721/solution/patch.diff b/tasks/livewire__livewire-10721/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..f1d399d6318cd3bb06f0b316971243b0d412cea2 --- /dev/null +++ b/tasks/livewire__livewire-10721/solution/patch.diff @@ -0,0 +1,165 @@ +diff --git a/src/Features/SupportComputed/BaseComputed.php b/src/Features/SupportComputed/BaseComputed.php +index 6c4df1e9..08cef725 100644 +--- a/src/Features/SupportComputed/BaseComputed.php ++++ b/src/Features/SupportComputed/BaseComputed.php +@@ -30,25 +30,14 @@ class BaseComputed extends Attribute + + public function handleMagicGet($returnValue) + { +- if ($this->persist) { +- $returnValue( +- $this->requestCachedValue ??= $this->handlePersistedGet() +- ); +- +- return; +- } +- +- if ($this->cache) { +- $returnValue( +- $this->requestCachedValue ??= $this->handleCachedGet() +- ); +- +- return; +- } +- +- $returnValue( +- $this->requestCachedValue ??= $this->evaluateComputed() +- ); ++ // The value is wrapped in an array so that "null" results are memoized too... ++ $this->requestCachedValue ??= [match (true) { ++ $this->persist => $this->handlePersistedGet(), ++ $this->cache => $this->handleCachedGet(), ++ default => $this->evaluateComputed(), ++ }]; ++ ++ $returnValue($this->requestCachedValue[0]); + } + + public function handleMagicUnset() +diff --git a/src/Features/SupportComputed/UnitTest.php b/src/Features/SupportComputed/UnitTest.php +index 4b9ec1ff..22b75048 100644 +--- a/src/Features/SupportComputed/UnitTest.php ++++ b/src/Features/SupportComputed/UnitTest.php +@@ -106,6 +106,122 @@ class UnitTest extends TestCase + ->assertSetStrict('count', 4); + } + ++ function test_computed_property_returning_null_is_memoized_within_a_single_request() ++ { ++ Livewire::test(new class extends TestComponent { ++ public $count = 0; ++ ++ #[Computed] ++ function foo() { ++ $this->count++; ++ ++ return null; ++ } ++ ++ function render() { ++ $noop = $this->foo; ++ $noop = $this->foo; ++ $noop = $this->foo; ++ ++ return <<<'HTML' ++
foo{{ $this->foo ?? 'null' }}
++ HTML; ++ } ++ }) ++ ->assertSee('foonull') ++ ->assertSetStrict('count', 1) ++ ->call('$refresh') ++ ->assertSetStrict('count', 2); ++ } ++ ++ function test_cached_computed_property_returning_null_is_memoized_within_a_single_request() ++ { ++ Cache::setDefaultDriver('array'); ++ ++ Livewire::test(new class extends TestComponent { ++ public $count = 0; ++ ++ #[Computed(cache: true)] ++ function foo() { ++ $this->count++; ++ ++ return null; ++ } ++ ++ function render() { ++ $noop = $this->foo; ++ $noop = $this->foo; ++ $noop = $this->foo; ++ ++ return <<<'HTML' ++
foo{{ $this->foo ?? 'null' }}
++ HTML; ++ } ++ }) ++ ->assertSee('foonull') ++ ->assertSetStrict('count', 1) ++ ->call('$refresh') ++ ->assertSetStrict('count', 2); ++ } ++ ++ function test_persisted_computed_property_returning_null_is_memoized_within_a_single_request() ++ { ++ Cache::setDefaultDriver('array'); ++ ++ Livewire::test(new class extends TestComponent { ++ public $count = 0; ++ ++ #[Computed(persist: true)] ++ function foo() { ++ $this->count++; ++ ++ return null; ++ } ++ ++ function render() { ++ $noop = $this->foo; ++ $noop = $this->foo; ++ $noop = $this->foo; ++ ++ return <<<'HTML' ++
foo{{ $this->foo ?? 'null' }}
++ HTML; ++ } ++ }) ++ ->assertSee('foonull') ++ ->assertSetStrict('count', 1) ++ ->call('$refresh') ++ ->assertSetStrict('count', 2); ++ } ++ ++ function test_can_bust_computed_property_returning_null_using_unset() ++ { ++ Livewire::test(new class extends TestComponent { ++ public $count = 0; ++ ++ #[Computed] ++ function foo() { ++ $this->count++; ++ ++ return null; ++ } ++ ++ function render() { ++ $noop = $this->foo; ++ unset($this->foo); ++ $noop = $this->foo; ++ ++ return <<<'HTML' ++
foo{{ $this->foo ?? 'null' }}
++ HTML; ++ } ++ }) ++ ->assertSee('foonull') ++ ->assertSetStrict('count', 2) ++ ->call('$refresh') ++ ->assertSetStrict('count', 4); ++ } ++ + function test_cached_computed_property_is_memoized_within_a_single_request() + { + Cache::setDefaultDriver('array'); diff --git a/tasks/livewire__livewire-10721/solution/solve.sh b/tasks/livewire__livewire-10721/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/livewire__livewire-10721/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/livewire__livewire-10721/task.toml b/tasks/livewire__livewire-10721/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..e60abb129106d098502e7f4cdb18ad2ee89fdfda --- /dev/null +++ b/tasks/livewire__livewire-10721/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/livewire__livewire-10721" +description = "[4.x] Memoize computed properties that return null within a request" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "livewire", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "livewire/livewire" +ref = "3bf965809bb5af9a0842cda1fb8a162b41ac9003" +reference = "https://github.com/livewire/livewire/pull/10721" +source_access = "auto" +built_at = "2026-11-16T16:09:51.393574+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:6b11254c7d1a1ce734ce39e944447ea3a506d627c4af0bd8b642759cd8d3a8b6" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-21T11:31:04Z" +diff_format = "unified" +context_files = [ + "src/Features/SupportComputed/BaseComputed.php", + "src/Features/SupportComputed/UnitTest.php", +] +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.420079+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:65c1b8420d092245064d9e01a30f8fcca28a246ff48793246c208ebec5b3b417" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/livewire__livewire-10721/tests/capture.py b/tasks/livewire__livewire-10721/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/livewire__livewire-10721/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/livewire__livewire-10721/tests/instruction.md b/tasks/livewire__livewire-10721/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8b05ce3acc037bc724e1595e103b299219c285df --- /dev/null +++ b/tasks/livewire__livewire-10721/tests/instruction.md @@ -0,0 +1,29 @@ +# Issue + +**Title:** [4.x] Memoize computed properties that return null within a request + +## Description + +Hi! + +I got bit by this in one of our apps, and then saw that it was actually affecting several other apps too. + +I think the fix is simple and safe, it was talked about [here](https://github.com/livewire/livewire/discussions/3164) and a similar fix was implemented . + +--- + +A `#[Computed]` property that returns `null` is never memoized. Its body re-runs on every read within the same request. Non-null values memoize fine. + +The per-request memo in `BaseComputed::handleMagicGet()` is stored with `??=`: + +```php +$returnValue( + $this->requestCachedValue ??= $this->evaluateComputed() +); +``` + +`??=` only assigns when the left side is null, so an honest `null` result (an `->first()` that finds nothing, an optional relation, a "current item" lookup with no match) looks the same as "not evaluated yet". Reading `$this->foo` four times in one request evaluates `foo()` four times. With this change it's once. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `3bf965809bb5`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10721/tests/oracle.patch b/tasks/livewire__livewire-10721/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..f1d399d6318cd3bb06f0b316971243b0d412cea2 --- /dev/null +++ b/tasks/livewire__livewire-10721/tests/oracle.patch @@ -0,0 +1,165 @@ +diff --git a/src/Features/SupportComputed/BaseComputed.php b/src/Features/SupportComputed/BaseComputed.php +index 6c4df1e9..08cef725 100644 +--- a/src/Features/SupportComputed/BaseComputed.php ++++ b/src/Features/SupportComputed/BaseComputed.php +@@ -30,25 +30,14 @@ class BaseComputed extends Attribute + + public function handleMagicGet($returnValue) + { +- if ($this->persist) { +- $returnValue( +- $this->requestCachedValue ??= $this->handlePersistedGet() +- ); +- +- return; +- } +- +- if ($this->cache) { +- $returnValue( +- $this->requestCachedValue ??= $this->handleCachedGet() +- ); +- +- return; +- } +- +- $returnValue( +- $this->requestCachedValue ??= $this->evaluateComputed() +- ); ++ // The value is wrapped in an array so that "null" results are memoized too... ++ $this->requestCachedValue ??= [match (true) { ++ $this->persist => $this->handlePersistedGet(), ++ $this->cache => $this->handleCachedGet(), ++ default => $this->evaluateComputed(), ++ }]; ++ ++ $returnValue($this->requestCachedValue[0]); + } + + public function handleMagicUnset() +diff --git a/src/Features/SupportComputed/UnitTest.php b/src/Features/SupportComputed/UnitTest.php +index 4b9ec1ff..22b75048 100644 +--- a/src/Features/SupportComputed/UnitTest.php ++++ b/src/Features/SupportComputed/UnitTest.php +@@ -106,6 +106,122 @@ class UnitTest extends TestCase + ->assertSetStrict('count', 4); + } + ++ function test_computed_property_returning_null_is_memoized_within_a_single_request() ++ { ++ Livewire::test(new class extends TestComponent { ++ public $count = 0; ++ ++ #[Computed] ++ function foo() { ++ $this->count++; ++ ++ return null; ++ } ++ ++ function render() { ++ $noop = $this->foo; ++ $noop = $this->foo; ++ $noop = $this->foo; ++ ++ return <<<'HTML' ++
foo{{ $this->foo ?? 'null' }}
++ HTML; ++ } ++ }) ++ ->assertSee('foonull') ++ ->assertSetStrict('count', 1) ++ ->call('$refresh') ++ ->assertSetStrict('count', 2); ++ } ++ ++ function test_cached_computed_property_returning_null_is_memoized_within_a_single_request() ++ { ++ Cache::setDefaultDriver('array'); ++ ++ Livewire::test(new class extends TestComponent { ++ public $count = 0; ++ ++ #[Computed(cache: true)] ++ function foo() { ++ $this->count++; ++ ++ return null; ++ } ++ ++ function render() { ++ $noop = $this->foo; ++ $noop = $this->foo; ++ $noop = $this->foo; ++ ++ return <<<'HTML' ++
foo{{ $this->foo ?? 'null' }}
++ HTML; ++ } ++ }) ++ ->assertSee('foonull') ++ ->assertSetStrict('count', 1) ++ ->call('$refresh') ++ ->assertSetStrict('count', 2); ++ } ++ ++ function test_persisted_computed_property_returning_null_is_memoized_within_a_single_request() ++ { ++ Cache::setDefaultDriver('array'); ++ ++ Livewire::test(new class extends TestComponent { ++ public $count = 0; ++ ++ #[Computed(persist: true)] ++ function foo() { ++ $this->count++; ++ ++ return null; ++ } ++ ++ function render() { ++ $noop = $this->foo; ++ $noop = $this->foo; ++ $noop = $this->foo; ++ ++ return <<<'HTML' ++
foo{{ $this->foo ?? 'null' }}
++ HTML; ++ } ++ }) ++ ->assertSee('foonull') ++ ->assertSetStrict('count', 1) ++ ->call('$refresh') ++ ->assertSetStrict('count', 2); ++ } ++ ++ function test_can_bust_computed_property_returning_null_using_unset() ++ { ++ Livewire::test(new class extends TestComponent { ++ public $count = 0; ++ ++ #[Computed] ++ function foo() { ++ $this->count++; ++ ++ return null; ++ } ++ ++ function render() { ++ $noop = $this->foo; ++ unset($this->foo); ++ $noop = $this->foo; ++ ++ return <<<'HTML' ++
foo{{ $this->foo ?? 'null' }}
++ HTML; ++ } ++ }) ++ ->assertSee('foonull') ++ ->assertSetStrict('count', 2) ++ ->call('$refresh') ++ ->assertSetStrict('count', 4); ++ } ++ + function test_cached_computed_property_is_memoized_within_a_single_request() + { + Cache::setDefaultDriver('array'); diff --git a/tasks/livewire__livewire-10721/tests/test.sh b/tasks/livewire__livewire-10721/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..44997c3f933c87434786b33595c4b04272dca7d6 --- /dev/null +++ b/tasks/livewire__livewire-10721/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 3bf965809bb5af9a0842cda1fb8a162b41ac9003 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/livewire__livewire-10721/tests/verifier.py b/tasks/livewire__livewire-10721/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/livewire__livewire-10721/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/livewire__livewire-10725/environment/Dockerfile b/tasks/livewire__livewire-10725/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..42451bf9810aa233dcbd3425d30e92180fbcaa4f --- /dev/null +++ b/tasks/livewire__livewire-10725/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/livewire/livewire.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/livewire/livewire.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/livewire/livewire.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 3bf965809bb5af9a0842cda1fb8a162b41ac9003 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 3bf965809bb5af9a0842cda1fb8a162b41ac9003 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 3bf965809bb5af9a0842cda1fb8a162b41ac9003 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/livewire__livewire-10725/instruction.md b/tasks/livewire__livewire-10725/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..99f769c2e8d687f782845ea55c8de44d0a978888 --- /dev/null +++ b/tasks/livewire__livewire-10725/instruction.md @@ -0,0 +1,20 @@ +# Issue + +**Title:** Stabilize loading delay browser test + +## Description + +The legacy loading-delay test checks each loader one millisecond after its timer threshold. CI repeatedly misses different thresholds on different PHP/Laravel shards, including on the workflow retry, while production loading code is unchanged. + +This keeps the regression coverage browser-observable but groups thresholds into wider timing windows. The fixture remains loading long enough to cover the 1000ms `longest` modifier, which also lets the previously skipped longest-delay assertion run again. + +Verification: +- Confirmed failures on five independent branch shards across the original and fresh full runs +- Failed selectors varied by shard and retry, establishing timing sensitivity rather than a production regression +- Focused LegacyBrowser test passed three consecutive local runs +- 1 test, 16 assertions per run +- `git diff --check` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `3bf965809bb5`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10725/solution/patch.diff b/tasks/livewire__livewire-10725/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..a410f57c7a5df3c98c541f41659a8af86cdb2f6d --- /dev/null +++ b/tasks/livewire__livewire-10725/solution/patch.diff @@ -0,0 +1,86 @@ +diff --git a/legacy_tests/Browser/Loading/ComponentWithLoadingDelays.php b/legacy_tests/Browser/Loading/ComponentWithLoadingDelays.php +index f39f7b3c..23b1b9bd 100644 +--- a/legacy_tests/Browser/Loading/ComponentWithLoadingDelays.php ++++ b/legacy_tests/Browser/Loading/ComponentWithLoadingDelays.php +@@ -10,8 +10,8 @@ class ComponentWithLoadingDelays extends BaseComponent + + public function hydrate() + { +- // Sleep for up to 1100ms as longest is 1000ms +- usleep(1000 * 1100); ++ // Sleep long enough to observe the 1000ms longest delay with room for browser scheduling. ++ usleep(1000 * 1500); + } + + public function render() +diff --git a/legacy_tests/Browser/Loading/Test.php b/legacy_tests/Browser/Loading/Test.php +index 39f20420..d1c3f891 100644 +--- a/legacy_tests/Browser/Loading/Test.php ++++ b/legacy_tests/Browser/Loading/Test.php +@@ -159,47 +159,34 @@ class Test extends TestCase + ->assertNotVisible('@delay-shortest') + ->waitForLivewire(function (Browser $browser) { + $browser->click('@load') +- ->assertNotVisible('@delay-shortest') +- ->assertVisible('@delay-none'); ++ ->waitFor('@delay-none'); + })->waitForLivewire(function (Browser $browser) { + $browser->click('@load') +- ->pause(51) +- ->assertNotVisible('@delay-shorter') +- ->assertVisible('@delay-shortest'); ++ ->pause(250) ++ ->assertNotVisible('@delay-long') ++ ->assertNotVisible('@delay-longer') ++ ->assertNotVisible('@delay-longest') ++ ->assertVisible('@delay-shortest') ++ ->assertVisible('@delay-shorter') ++ ->assertVisible('@delay-short') ++ ->assertVisible('@delay') ++ ->assertVisible('@delay-default'); + })->waitForLivewire(function (Browser $browser) { + $browser->click('@load') +- ->pause(101) +- ->assertNotVisible('@delay-short') +- ->assertVisible('@delay-shorter'); ++ ->pause(400) ++ ->assertNotVisible('@delay-longer') ++ ->assertNotVisible('@delay-longest') ++ ->assertVisible('@delay-long'); + })->waitForLivewire(function (Browser $browser) { + $browser->click('@load') +- ->pause(151) +- ->assertNotVisible('@delay') +- ->assertNotVisible('@delay-default') +- ->assertVisible('@delay-short'); ++ ->pause(750) ++ ->assertNotVisible('@delay-longest') ++ ->assertVisible('@delay-longer'); + })->waitForLivewire(function (Browser $browser) { + $browser->click('@load') +- ->pause(201) +- ->assertNotVisible('@delay-long') +- ->assertVisible('@delay') +- ->assertVisible('@delay-default'); +- })->waitForLivewire(function (Browser $browser) { +- $browser->click('@load') +- ->pause(301) +- ->assertNotVisible('@delay-longer') +- ->assertVisible('@delay-long'); +- })->waitForLivewire(function (Browser $browser) { +- $browser->click('@load') +- ->pause(501) +- ->assertNotVisible('@delay-longest') +- ->assertVisible('@delay-longer'); ++ ->pause(1250) ++ ->assertVisible('@delay-longest'); + }); +- // @todo: this is flaky... +- // })->waitForLivewire(function (Browser $browser) { +- // $browser->click('@load') +- // ->pause(1002) +- // ->assertVisible('@delay-longest'); +- // }); + }); + } + diff --git a/tasks/livewire__livewire-10725/solution/solve.sh b/tasks/livewire__livewire-10725/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/livewire__livewire-10725/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/livewire__livewire-10725/task.toml b/tasks/livewire__livewire-10725/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..5abcd97570d22aad9836811ab244deae64fa386c --- /dev/null +++ b/tasks/livewire__livewire-10725/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/livewire__livewire-10725" +description = "Stabilize loading delay browser test" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "livewire", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "livewire/livewire" +ref = "3bf965809bb5af9a0842cda1fb8a162b41ac9003" +reference = "https://github.com/livewire/livewire/pull/10725" +source_access = "auto" +built_at = "2026-11-16T16:09:51.471083+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:8c6ad2a58a250110ffa6c2e783656dbbfe9f92a87465f3de35257f7a8bb9e591" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-17T19:44:10Z" +diff_format = "unified" +context_files = [ + "legacy_tests/Browser/Loading/ComponentWithLoadingDelays.php", + "legacy_tests/Browser/Loading/Test.php", +] +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.420571+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:65c1b8420d092245064d9e01a30f8fcca28a246ff48793246c208ebec5b3b417" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/livewire__livewire-10725/tests/capture.py b/tasks/livewire__livewire-10725/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/livewire__livewire-10725/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/livewire__livewire-10725/tests/instruction.md b/tasks/livewire__livewire-10725/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..99f769c2e8d687f782845ea55c8de44d0a978888 --- /dev/null +++ b/tasks/livewire__livewire-10725/tests/instruction.md @@ -0,0 +1,20 @@ +# Issue + +**Title:** Stabilize loading delay browser test + +## Description + +The legacy loading-delay test checks each loader one millisecond after its timer threshold. CI repeatedly misses different thresholds on different PHP/Laravel shards, including on the workflow retry, while production loading code is unchanged. + +This keeps the regression coverage browser-observable but groups thresholds into wider timing windows. The fixture remains loading long enough to cover the 1000ms `longest` modifier, which also lets the previously skipped longest-delay assertion run again. + +Verification: +- Confirmed failures on five independent branch shards across the original and fresh full runs +- Failed selectors varied by shard and retry, establishing timing sensitivity rather than a production regression +- Focused LegacyBrowser test passed three consecutive local runs +- 1 test, 16 assertions per run +- `git diff --check` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `3bf965809bb5`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10725/tests/oracle.patch b/tasks/livewire__livewire-10725/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..a410f57c7a5df3c98c541f41659a8af86cdb2f6d --- /dev/null +++ b/tasks/livewire__livewire-10725/tests/oracle.patch @@ -0,0 +1,86 @@ +diff --git a/legacy_tests/Browser/Loading/ComponentWithLoadingDelays.php b/legacy_tests/Browser/Loading/ComponentWithLoadingDelays.php +index f39f7b3c..23b1b9bd 100644 +--- a/legacy_tests/Browser/Loading/ComponentWithLoadingDelays.php ++++ b/legacy_tests/Browser/Loading/ComponentWithLoadingDelays.php +@@ -10,8 +10,8 @@ class ComponentWithLoadingDelays extends BaseComponent + + public function hydrate() + { +- // Sleep for up to 1100ms as longest is 1000ms +- usleep(1000 * 1100); ++ // Sleep long enough to observe the 1000ms longest delay with room for browser scheduling. ++ usleep(1000 * 1500); + } + + public function render() +diff --git a/legacy_tests/Browser/Loading/Test.php b/legacy_tests/Browser/Loading/Test.php +index 39f20420..d1c3f891 100644 +--- a/legacy_tests/Browser/Loading/Test.php ++++ b/legacy_tests/Browser/Loading/Test.php +@@ -159,47 +159,34 @@ class Test extends TestCase + ->assertNotVisible('@delay-shortest') + ->waitForLivewire(function (Browser $browser) { + $browser->click('@load') +- ->assertNotVisible('@delay-shortest') +- ->assertVisible('@delay-none'); ++ ->waitFor('@delay-none'); + })->waitForLivewire(function (Browser $browser) { + $browser->click('@load') +- ->pause(51) +- ->assertNotVisible('@delay-shorter') +- ->assertVisible('@delay-shortest'); ++ ->pause(250) ++ ->assertNotVisible('@delay-long') ++ ->assertNotVisible('@delay-longer') ++ ->assertNotVisible('@delay-longest') ++ ->assertVisible('@delay-shortest') ++ ->assertVisible('@delay-shorter') ++ ->assertVisible('@delay-short') ++ ->assertVisible('@delay') ++ ->assertVisible('@delay-default'); + })->waitForLivewire(function (Browser $browser) { + $browser->click('@load') +- ->pause(101) +- ->assertNotVisible('@delay-short') +- ->assertVisible('@delay-shorter'); ++ ->pause(400) ++ ->assertNotVisible('@delay-longer') ++ ->assertNotVisible('@delay-longest') ++ ->assertVisible('@delay-long'); + })->waitForLivewire(function (Browser $browser) { + $browser->click('@load') +- ->pause(151) +- ->assertNotVisible('@delay') +- ->assertNotVisible('@delay-default') +- ->assertVisible('@delay-short'); ++ ->pause(750) ++ ->assertNotVisible('@delay-longest') ++ ->assertVisible('@delay-longer'); + })->waitForLivewire(function (Browser $browser) { + $browser->click('@load') +- ->pause(201) +- ->assertNotVisible('@delay-long') +- ->assertVisible('@delay') +- ->assertVisible('@delay-default'); +- })->waitForLivewire(function (Browser $browser) { +- $browser->click('@load') +- ->pause(301) +- ->assertNotVisible('@delay-longer') +- ->assertVisible('@delay-long'); +- })->waitForLivewire(function (Browser $browser) { +- $browser->click('@load') +- ->pause(501) +- ->assertNotVisible('@delay-longest') +- ->assertVisible('@delay-longer'); ++ ->pause(1250) ++ ->assertVisible('@delay-longest'); + }); +- // @todo: this is flaky... +- // })->waitForLivewire(function (Browser $browser) { +- // $browser->click('@load') +- // ->pause(1002) +- // ->assertVisible('@delay-longest'); +- // }); + }); + } + diff --git a/tasks/livewire__livewire-10725/tests/test.sh b/tasks/livewire__livewire-10725/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..44997c3f933c87434786b33595c4b04272dca7d6 --- /dev/null +++ b/tasks/livewire__livewire-10725/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 3bf965809bb5af9a0842cda1fb8a162b41ac9003 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/livewire__livewire-10725/tests/verifier.py b/tasks/livewire__livewire-10725/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/livewire__livewire-10725/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/livewire__livewire-10726/environment/Dockerfile b/tasks/livewire__livewire-10726/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..3eafe51cf8d74a3b75f1d057068a8c1e412f4d98 --- /dev/null +++ b/tasks/livewire__livewire-10726/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/livewire/livewire.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/livewire/livewire.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/livewire/livewire.git +WORKDIR /workspace +RUN git fetch --depth 1 origin f4a31f27df9100c00589b9f4bedb0967b96620c4 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard f4a31f27df9100c00589b9f4bedb0967b96620c4 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base f4a31f27df9100c00589b9f4bedb0967b96620c4 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/livewire__livewire-10726/instruction.md b/tasks/livewire__livewire-10726/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a5c7e1bd716e2787a424ca04989abebb413bdca0 --- /dev/null +++ b/tasks/livewire__livewire-10726/instruction.md @@ -0,0 +1,19 @@ +# Issue + +**Title:** [4.x] Stabilize loading delay browser test + +## Description + +The legacy loading-delay test checks each loader one millisecond after its timer threshold. Recent `4.x` primary runs repeatedly miss different thresholds on different PHP/Laravel shards, including on the workflow retry, while production loading code is unchanged. + +This ports #10725 to `4.x`. It keeps the coverage browser-observable but groups thresholds into wider timing windows. The fixture remains loading long enough to cover the 1000ms `longest` modifier, which also restores the previously skipped longest-delay assertion. + +Verification: +- Confirmed failures across multiple `4.x` primary runs and different selectors +- Focused `4.x` LegacyBrowser test: 1 test, 16 assertions, green +- Equivalent `main` patch passed three consecutive focused browser runs +- `git diff --check` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `f4a31f27df91`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10726/solution/patch.diff b/tasks/livewire__livewire-10726/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..a410f57c7a5df3c98c541f41659a8af86cdb2f6d --- /dev/null +++ b/tasks/livewire__livewire-10726/solution/patch.diff @@ -0,0 +1,86 @@ +diff --git a/legacy_tests/Browser/Loading/ComponentWithLoadingDelays.php b/legacy_tests/Browser/Loading/ComponentWithLoadingDelays.php +index f39f7b3c..23b1b9bd 100644 +--- a/legacy_tests/Browser/Loading/ComponentWithLoadingDelays.php ++++ b/legacy_tests/Browser/Loading/ComponentWithLoadingDelays.php +@@ -10,8 +10,8 @@ class ComponentWithLoadingDelays extends BaseComponent + + public function hydrate() + { +- // Sleep for up to 1100ms as longest is 1000ms +- usleep(1000 * 1100); ++ // Sleep long enough to observe the 1000ms longest delay with room for browser scheduling. ++ usleep(1000 * 1500); + } + + public function render() +diff --git a/legacy_tests/Browser/Loading/Test.php b/legacy_tests/Browser/Loading/Test.php +index 39f20420..d1c3f891 100644 +--- a/legacy_tests/Browser/Loading/Test.php ++++ b/legacy_tests/Browser/Loading/Test.php +@@ -159,47 +159,34 @@ class Test extends TestCase + ->assertNotVisible('@delay-shortest') + ->waitForLivewire(function (Browser $browser) { + $browser->click('@load') +- ->assertNotVisible('@delay-shortest') +- ->assertVisible('@delay-none'); ++ ->waitFor('@delay-none'); + })->waitForLivewire(function (Browser $browser) { + $browser->click('@load') +- ->pause(51) +- ->assertNotVisible('@delay-shorter') +- ->assertVisible('@delay-shortest'); ++ ->pause(250) ++ ->assertNotVisible('@delay-long') ++ ->assertNotVisible('@delay-longer') ++ ->assertNotVisible('@delay-longest') ++ ->assertVisible('@delay-shortest') ++ ->assertVisible('@delay-shorter') ++ ->assertVisible('@delay-short') ++ ->assertVisible('@delay') ++ ->assertVisible('@delay-default'); + })->waitForLivewire(function (Browser $browser) { + $browser->click('@load') +- ->pause(101) +- ->assertNotVisible('@delay-short') +- ->assertVisible('@delay-shorter'); ++ ->pause(400) ++ ->assertNotVisible('@delay-longer') ++ ->assertNotVisible('@delay-longest') ++ ->assertVisible('@delay-long'); + })->waitForLivewire(function (Browser $browser) { + $browser->click('@load') +- ->pause(151) +- ->assertNotVisible('@delay') +- ->assertNotVisible('@delay-default') +- ->assertVisible('@delay-short'); ++ ->pause(750) ++ ->assertNotVisible('@delay-longest') ++ ->assertVisible('@delay-longer'); + })->waitForLivewire(function (Browser $browser) { + $browser->click('@load') +- ->pause(201) +- ->assertNotVisible('@delay-long') +- ->assertVisible('@delay') +- ->assertVisible('@delay-default'); +- })->waitForLivewire(function (Browser $browser) { +- $browser->click('@load') +- ->pause(301) +- ->assertNotVisible('@delay-longer') +- ->assertVisible('@delay-long'); +- })->waitForLivewire(function (Browser $browser) { +- $browser->click('@load') +- ->pause(501) +- ->assertNotVisible('@delay-longest') +- ->assertVisible('@delay-longer'); ++ ->pause(1250) ++ ->assertVisible('@delay-longest'); + }); +- // @todo: this is flaky... +- // })->waitForLivewire(function (Browser $browser) { +- // $browser->click('@load') +- // ->pause(1002) +- // ->assertVisible('@delay-longest'); +- // }); + }); + } + diff --git a/tasks/livewire__livewire-10726/solution/solve.sh b/tasks/livewire__livewire-10726/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/livewire__livewire-10726/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/livewire__livewire-10726/task.toml b/tasks/livewire__livewire-10726/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..d7de0246ec0343e9fdc02e25aecfb38e909b5095 --- /dev/null +++ b/tasks/livewire__livewire-10726/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/livewire__livewire-10726" +description = "[4.x] Stabilize loading delay browser test" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "livewire", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "livewire/livewire" +ref = "f4a31f27df9100c00589b9f4bedb0967b96620c4" +reference = "https://github.com/livewire/livewire/pull/10726" +source_access = "auto" +built_at = "2026-11-16T16:09:51.469618+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:16bd4b1bb2225c51b6acacbbe0fc3b6fe2871d00a9970347d8a8b7f9c081b496" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-17T19:44:37Z" +diff_format = "unified" +context_files = [ + "legacy_tests/Browser/Loading/ComponentWithLoadingDelays.php", + "legacy_tests/Browser/Loading/Test.php", +] +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.421088+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:5f51d7ce43b144759a6767cedba2152a8fb8c50ad7a71313083a36b6fa5845b6" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/livewire__livewire-10726/tests/capture.py b/tasks/livewire__livewire-10726/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/livewire__livewire-10726/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/livewire__livewire-10726/tests/instruction.md b/tasks/livewire__livewire-10726/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a5c7e1bd716e2787a424ca04989abebb413bdca0 --- /dev/null +++ b/tasks/livewire__livewire-10726/tests/instruction.md @@ -0,0 +1,19 @@ +# Issue + +**Title:** [4.x] Stabilize loading delay browser test + +## Description + +The legacy loading-delay test checks each loader one millisecond after its timer threshold. Recent `4.x` primary runs repeatedly miss different thresholds on different PHP/Laravel shards, including on the workflow retry, while production loading code is unchanged. + +This ports #10725 to `4.x`. It keeps the coverage browser-observable but groups thresholds into wider timing windows. The fixture remains loading long enough to cover the 1000ms `longest` modifier, which also restores the previously skipped longest-delay assertion. + +Verification: +- Confirmed failures across multiple `4.x` primary runs and different selectors +- Focused `4.x` LegacyBrowser test: 1 test, 16 assertions, green +- Equivalent `main` patch passed three consecutive focused browser runs +- `git diff --check` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `f4a31f27df91`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10726/tests/oracle.patch b/tasks/livewire__livewire-10726/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..a410f57c7a5df3c98c541f41659a8af86cdb2f6d --- /dev/null +++ b/tasks/livewire__livewire-10726/tests/oracle.patch @@ -0,0 +1,86 @@ +diff --git a/legacy_tests/Browser/Loading/ComponentWithLoadingDelays.php b/legacy_tests/Browser/Loading/ComponentWithLoadingDelays.php +index f39f7b3c..23b1b9bd 100644 +--- a/legacy_tests/Browser/Loading/ComponentWithLoadingDelays.php ++++ b/legacy_tests/Browser/Loading/ComponentWithLoadingDelays.php +@@ -10,8 +10,8 @@ class ComponentWithLoadingDelays extends BaseComponent + + public function hydrate() + { +- // Sleep for up to 1100ms as longest is 1000ms +- usleep(1000 * 1100); ++ // Sleep long enough to observe the 1000ms longest delay with room for browser scheduling. ++ usleep(1000 * 1500); + } + + public function render() +diff --git a/legacy_tests/Browser/Loading/Test.php b/legacy_tests/Browser/Loading/Test.php +index 39f20420..d1c3f891 100644 +--- a/legacy_tests/Browser/Loading/Test.php ++++ b/legacy_tests/Browser/Loading/Test.php +@@ -159,47 +159,34 @@ class Test extends TestCase + ->assertNotVisible('@delay-shortest') + ->waitForLivewire(function (Browser $browser) { + $browser->click('@load') +- ->assertNotVisible('@delay-shortest') +- ->assertVisible('@delay-none'); ++ ->waitFor('@delay-none'); + })->waitForLivewire(function (Browser $browser) { + $browser->click('@load') +- ->pause(51) +- ->assertNotVisible('@delay-shorter') +- ->assertVisible('@delay-shortest'); ++ ->pause(250) ++ ->assertNotVisible('@delay-long') ++ ->assertNotVisible('@delay-longer') ++ ->assertNotVisible('@delay-longest') ++ ->assertVisible('@delay-shortest') ++ ->assertVisible('@delay-shorter') ++ ->assertVisible('@delay-short') ++ ->assertVisible('@delay') ++ ->assertVisible('@delay-default'); + })->waitForLivewire(function (Browser $browser) { + $browser->click('@load') +- ->pause(101) +- ->assertNotVisible('@delay-short') +- ->assertVisible('@delay-shorter'); ++ ->pause(400) ++ ->assertNotVisible('@delay-longer') ++ ->assertNotVisible('@delay-longest') ++ ->assertVisible('@delay-long'); + })->waitForLivewire(function (Browser $browser) { + $browser->click('@load') +- ->pause(151) +- ->assertNotVisible('@delay') +- ->assertNotVisible('@delay-default') +- ->assertVisible('@delay-short'); ++ ->pause(750) ++ ->assertNotVisible('@delay-longest') ++ ->assertVisible('@delay-longer'); + })->waitForLivewire(function (Browser $browser) { + $browser->click('@load') +- ->pause(201) +- ->assertNotVisible('@delay-long') +- ->assertVisible('@delay') +- ->assertVisible('@delay-default'); +- })->waitForLivewire(function (Browser $browser) { +- $browser->click('@load') +- ->pause(301) +- ->assertNotVisible('@delay-longer') +- ->assertVisible('@delay-long'); +- })->waitForLivewire(function (Browser $browser) { +- $browser->click('@load') +- ->pause(501) +- ->assertNotVisible('@delay-longest') +- ->assertVisible('@delay-longer'); ++ ->pause(1250) ++ ->assertVisible('@delay-longest'); + }); +- // @todo: this is flaky... +- // })->waitForLivewire(function (Browser $browser) { +- // $browser->click('@load') +- // ->pause(1002) +- // ->assertVisible('@delay-longest'); +- // }); + }); + } + diff --git a/tasks/livewire__livewire-10726/tests/test.sh b/tasks/livewire__livewire-10726/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ff476d8bea967eb092ba18f2241d05af1d592c87 --- /dev/null +++ b/tasks/livewire__livewire-10726/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace f4a31f27df9100c00589b9f4bedb0967b96620c4 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/livewire__livewire-10726/tests/verifier.py b/tasks/livewire__livewire-10726/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/livewire__livewire-10726/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/livewire__livewire-10728/environment/Dockerfile b/tasks/livewire__livewire-10728/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2b0e159ee8ce195ce98a086105e83d9d0bd84fd4 --- /dev/null +++ b/tasks/livewire__livewire-10728/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/livewire/livewire.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/livewire/livewire.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/livewire/livewire.git +WORKDIR /workspace +RUN git fetch --depth 1 origin d0b4e22841d362dd213ee9602c399594d387b6ee 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard d0b4e22841d362dd213ee9602c399594d387b6ee \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base d0b4e22841d362dd213ee9602c399594d387b6ee \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/livewire__livewire-10728/instruction.md b/tasks/livewire__livewire-10728/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b029579c27cd11634225a7b641dd97ca40d14dde --- /dev/null +++ b/tasks/livewire__livewire-10728/instruction.md @@ -0,0 +1,22 @@ +# Issue + +**Title:** [4.x] Speed up synth resolution by not building an exception on every getKey() call + +## Description + +`Synth::getKey()` guards against a missing `$key` using `throw_unless()`, but the exception passed to it is built on every call, whether it gets thrown or not. Building an exception captures a stack trace, and `getKey()` runs for every synthesized value on both dehydrate (to write the `s` meta) and hydrate (to find the synth for a key). On components with collections or nested synthesized state, that adds up to most of the time spent resolving synths. + +This PR only builds the exception when the key is actually missing. Behavior is unchanged. + +Benchmark (1,000 iterations, component with a 40-item collection, Carbon, Stringable, stdClass, int and string properties): + +| | Before | After | +|---|---:|---:| +| Mount | 0.48ms | 0.38ms | +| Update | 1.65ms | 0.55ms | + +This originally added three resolution caches to `HandleSynths` plus a benchmark test. Profiling showed the speedup came from skipping `getKey()`, so the caches weren't needed and this one-line fix replaces them. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d0b4e22841d3`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10728/solution/patch.diff b/tasks/livewire__livewire-10728/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..784bed86e946bc0429cb953178b92734799c145c --- /dev/null +++ b/tasks/livewire__livewire-10728/solution/patch.diff @@ -0,0 +1,18 @@ +diff --git a/src/Mechanisms/HandleComponents/Synthesizers/Synth.php b/src/Mechanisms/HandleComponents/Synthesizers/Synth.php +index 1bfd4ce4..a9851929 100644 +--- a/src/Mechanisms/HandleComponents/Synthesizers/Synth.php ++++ b/src/Mechanisms/HandleComponents/Synthesizers/Synth.php +@@ -11,10 +11,9 @@ abstract class Synth { + ) {} + + public static function getKey() { +- throw_unless( +- property_exists(static::class, 'key'), +- new \Exception('You need to define static $key property on: '.static::class) +- ); ++ if (! property_exists(static::class, 'key')) { ++ throw new \Exception('You need to define static $key property on: '.static::class); ++ } + + return static::$key; + } diff --git a/tasks/livewire__livewire-10728/solution/solve.sh b/tasks/livewire__livewire-10728/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/livewire__livewire-10728/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/livewire__livewire-10728/task.toml b/tasks/livewire__livewire-10728/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..d45091a939413664522bf6618ddaeb5761195b62 --- /dev/null +++ b/tasks/livewire__livewire-10728/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/livewire__livewire-10728" +description = "[4.x] Speed up synth resolution by not building an exception on every getKey() call" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "livewire", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "livewire/livewire" +ref = "d0b4e22841d362dd213ee9602c399594d387b6ee" +reference = "https://github.com/livewire/livewire/pull/10728" +source_access = "auto" +built_at = "2026-11-16T16:09:51.422260+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:914cd953f0df645996a2a15f86c93ffdc5b4d0c2f8664882377a176dffea2fda" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-10-07T11:49:18Z" +diff_format = "unified" +context_files = [ + "src/Mechanisms/HandleComponents/Synthesizers/Synth.php", +] +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.421578+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:108fd5bbaa619e83c7b309cc26c21beaddb12766fe0d939f64edd86f874f671a" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/livewire__livewire-10728/tests/capture.py b/tasks/livewire__livewire-10728/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/livewire__livewire-10728/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/livewire__livewire-10728/tests/instruction.md b/tasks/livewire__livewire-10728/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b029579c27cd11634225a7b641dd97ca40d14dde --- /dev/null +++ b/tasks/livewire__livewire-10728/tests/instruction.md @@ -0,0 +1,22 @@ +# Issue + +**Title:** [4.x] Speed up synth resolution by not building an exception on every getKey() call + +## Description + +`Synth::getKey()` guards against a missing `$key` using `throw_unless()`, but the exception passed to it is built on every call, whether it gets thrown or not. Building an exception captures a stack trace, and `getKey()` runs for every synthesized value on both dehydrate (to write the `s` meta) and hydrate (to find the synth for a key). On components with collections or nested synthesized state, that adds up to most of the time spent resolving synths. + +This PR only builds the exception when the key is actually missing. Behavior is unchanged. + +Benchmark (1,000 iterations, component with a 40-item collection, Carbon, Stringable, stdClass, int and string properties): + +| | Before | After | +|---|---:|---:| +| Mount | 0.48ms | 0.38ms | +| Update | 1.65ms | 0.55ms | + +This originally added three resolution caches to `HandleSynths` plus a benchmark test. Profiling showed the speedup came from skipping `getKey()`, so the caches weren't needed and this one-line fix replaces them. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d0b4e22841d3`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10728/tests/oracle.patch b/tasks/livewire__livewire-10728/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..784bed86e946bc0429cb953178b92734799c145c --- /dev/null +++ b/tasks/livewire__livewire-10728/tests/oracle.patch @@ -0,0 +1,18 @@ +diff --git a/src/Mechanisms/HandleComponents/Synthesizers/Synth.php b/src/Mechanisms/HandleComponents/Synthesizers/Synth.php +index 1bfd4ce4..a9851929 100644 +--- a/src/Mechanisms/HandleComponents/Synthesizers/Synth.php ++++ b/src/Mechanisms/HandleComponents/Synthesizers/Synth.php +@@ -11,10 +11,9 @@ abstract class Synth { + ) {} + + public static function getKey() { +- throw_unless( +- property_exists(static::class, 'key'), +- new \Exception('You need to define static $key property on: '.static::class) +- ); ++ if (! property_exists(static::class, 'key')) { ++ throw new \Exception('You need to define static $key property on: '.static::class); ++ } + + return static::$key; + } diff --git a/tasks/livewire__livewire-10728/tests/test.sh b/tasks/livewire__livewire-10728/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..f4255995d98bc2c91067af5b4e4a6a330f30ec75 --- /dev/null +++ b/tasks/livewire__livewire-10728/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace d0b4e22841d362dd213ee9602c399594d387b6ee > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/livewire__livewire-10728/tests/verifier.py b/tasks/livewire__livewire-10728/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/livewire__livewire-10728/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/livewire__livewire-10730/environment/Dockerfile b/tasks/livewire__livewire-10730/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..4caeb68e48d79b778ef576d83ae40a9c8f86983c --- /dev/null +++ b/tasks/livewire__livewire-10730/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/livewire/livewire.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/livewire/livewire.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/livewire/livewire.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 279ce07924bf1aa94e959864a433b38eee953176 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 279ce07924bf1aa94e959864a433b38eee953176 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 279ce07924bf1aa94e959864a433b38eee953176 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/livewire__livewire-10730/instruction.md b/tasks/livewire__livewire-10730/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..251eb2a84783e684e1e585dfe96ae72586ca5693 --- /dev/null +++ b/tasks/livewire__livewire-10730/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** Update Alpine to v3.17.4 on main + +## Description + +Updates Alpine and all ten bundled plugin constraints to `^3.17.4`, then refreshes `package-lock.json` from the published npm registry artifacts. + +Verified all eleven lock entries resolve to v3.17.4 with registry URLs and integrity metadata. `npm ci`, the production build, and the JavaScript suite pass locally: 164 tests passed with one skipped. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `279ce07924bf`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10730/solution/patch.diff b/tasks/livewire__livewire-10730/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..d3a39550935244745aabef9e67abde8f9424819d --- /dev/null +++ b/tasks/livewire__livewire-10730/solution/patch.diff @@ -0,0 +1,185 @@ +diff --git a/package-lock.json b/package-lock.json +index dd397950..2862a828 100644 +--- a/package-lock.json ++++ b/package-lock.json +@@ -7,18 +7,18 @@ + "name": "laravel-livewire", + "license": "MIT", + "dependencies": { +- "@alpinejs/anchor": "^3.17.3", +- "@alpinejs/collapse": "^3.17.3", +- "@alpinejs/csp": "^3.17.3", +- "@alpinejs/focus": "^3.17.3", +- "@alpinejs/intersect": "^3.17.3", +- "@alpinejs/mask": "^3.17.3", +- "@alpinejs/morph": "^3.17.3", +- "@alpinejs/persist": "^3.17.3", +- "@alpinejs/resize": "^3.17.3", +- "@alpinejs/sort": "^3.17.3", ++ "@alpinejs/anchor": "^3.17.4", ++ "@alpinejs/collapse": "^3.17.4", ++ "@alpinejs/csp": "^3.17.4", ++ "@alpinejs/focus": "^3.17.4", ++ "@alpinejs/intersect": "^3.17.4", ++ "@alpinejs/mask": "^3.17.4", ++ "@alpinejs/morph": "^3.17.4", ++ "@alpinejs/persist": "^3.17.4", ++ "@alpinejs/resize": "^3.17.4", ++ "@alpinejs/sort": "^3.17.4", + "@vue/reactivity": "^3.2.45", +- "alpinejs": "^3.17.3", ++ "alpinejs": "^3.17.4", + "nprogress": "^0.2.0" + }, + "devDependencies": { +@@ -29,33 +29,33 @@ + } + }, + "node_modules/@alpinejs/anchor": { +- "version": "3.17.3", +- "resolved": "https://registry.npmjs.org/@alpinejs/anchor/-/anchor-3.17.3.tgz", +- "integrity": "sha512-BeKw+NCjkni6pya8jMZpPeL429L+qoSHIUs15LCbPF03bsANyWjUIC2jZ85PX+y6X9hjI1k4GQUIHwI/yRtWXw==", ++ "version": "3.17.4", ++ "resolved": "https://registry.npmjs.org/@alpinejs/anchor/-/anchor-3.17.4.tgz", ++ "integrity": "sha512-sHCML94TM7fugZucIJBb+vyw/igMdd3ZawGe/daoD1OIzTtJe0ShgFAzqG6Wj1gilZwV/HrI5P/OWovMSd76WQ==", + "license": "MIT", + "dependencies": { + "@floating-ui/dom": "^1.5.3" + } + }, + "node_modules/@alpinejs/collapse": { +- "version": "3.17.3", +- "resolved": "https://registry.npmjs.org/@alpinejs/collapse/-/collapse-3.17.3.tgz", +- "integrity": "sha512-pAROM7iHkwDtKmqWrWFII5/cOD4M/oTi3UyS0b8mNOLjIsNZ1YO32K+6rpwpuBfRAZgNxU0K1UntuLR9+p9Log==", ++ "version": "3.17.4", ++ "resolved": "https://registry.npmjs.org/@alpinejs/collapse/-/collapse-3.17.4.tgz", ++ "integrity": "sha512-Us4cE8jHzKtRs4mYNbmX4art/Hpm90vIGH6h5Mcv1EWK9Dgg48RNzSlPFt9F/D6bk2onbdeagYayqEvzpPbqPg==", + "license": "MIT" + }, + "node_modules/@alpinejs/csp": { +- "version": "3.17.3", +- "resolved": "https://registry.npmjs.org/@alpinejs/csp/-/csp-3.17.3.tgz", +- "integrity": "sha512-Y24sCNahmtdfSp4awWBRmdqHfWrZPfuoa++0YqI6BuEaZ/Xjn8BOuBOScO+fzCXK0V2Vo9Ryy9tWQnTIVMyObQ==", ++ "version": "3.17.4", ++ "resolved": "https://registry.npmjs.org/@alpinejs/csp/-/csp-3.17.4.tgz", ++ "integrity": "sha512-SlRXmqO6kYhnxlg+99etmuzJtE9Lk4QbKjBHqerXzaMflJqoJXdz/SI3IvHJGZ/vRVyC3bR0SSBz40oY7goBeg==", + "license": "MIT", + "dependencies": { + "@vue/reactivity": "~3.5.40" + } + }, + "node_modules/@alpinejs/focus": { +- "version": "3.17.3", +- "resolved": "https://registry.npmjs.org/@alpinejs/focus/-/focus-3.17.3.tgz", +- "integrity": "sha512-d91S3KiSnOyrMBfKsWoHKEw+ZPlVWHkaHBQgwPDOFgdVAxFsvZXEXi1EzX0QbOtLW9HqQwcFiqxoxRgs59UNyg==", ++ "version": "3.17.4", ++ "resolved": "https://registry.npmjs.org/@alpinejs/focus/-/focus-3.17.4.tgz", ++ "integrity": "sha512-IpZuMQC+nk9xEr9lfqzI+m7Pwti3dfiYhB4UrRIbO2KurezOM5HppYYXVtRQ1mD7L3R7rGtjAQksvWpCnk3lGw==", + "license": "MIT", + "dependencies": { + "focus-trap": "^8.0.0", +@@ -63,39 +63,39 @@ + } + }, + "node_modules/@alpinejs/intersect": { +- "version": "3.17.3", +- "resolved": "https://registry.npmjs.org/@alpinejs/intersect/-/intersect-3.17.3.tgz", +- "integrity": "sha512-uBlcZ5UnEPGVlGCdXHguPgwMiBZJqNA1vrIBvbP6qBjeYJx4nE4YlWQztXBTJgZbU5BtWKo9pGZbzvFOlX+T/Q==", ++ "version": "3.17.4", ++ "resolved": "https://registry.npmjs.org/@alpinejs/intersect/-/intersect-3.17.4.tgz", ++ "integrity": "sha512-soIfavWRHh1dEs05z6wkKtYf8i/ohIG1EDo51urbURj8HifVLV8hd4oCVEGlKwEwt6NXBZDhWMhKk9SM//JHtQ==", + "license": "MIT" + }, + "node_modules/@alpinejs/mask": { +- "version": "3.17.3", +- "resolved": "https://registry.npmjs.org/@alpinejs/mask/-/mask-3.17.3.tgz", +- "integrity": "sha512-u8CD0FnmCApoqcZEr/6lOnrZzh4noVbiI+nEGIqhc9rj8ZA7rCt+Gtr6WDSsf5Dg1thTIfe5ykDg/WseiZl64g==", ++ "version": "3.17.4", ++ "resolved": "https://registry.npmjs.org/@alpinejs/mask/-/mask-3.17.4.tgz", ++ "integrity": "sha512-eEcggxA8+TlpMYoioF43vhLuoInL8rlkPpAZmIWh4SRLJwZRaxCYrb8W+A3kyiRos7z8Bfj2FHwJmq+jejfKaw==", + "license": "MIT" + }, + "node_modules/@alpinejs/morph": { +- "version": "3.17.3", +- "resolved": "https://registry.npmjs.org/@alpinejs/morph/-/morph-3.17.3.tgz", +- "integrity": "sha512-1oW48NjXKjLLzg4o7avVbZMz/pd7/pvlVHNOtF15pxVf5VUUg8Jq5F0wN8+eSlmU+LxyF3XWOZDtOEwY8/O1Aw==", ++ "version": "3.17.4", ++ "resolved": "https://registry.npmjs.org/@alpinejs/morph/-/morph-3.17.4.tgz", ++ "integrity": "sha512-0jjisxp/ErYv3yRFIccViLgJa+BODm8aBBS/kUBp62+qd4rJ5c6mJ1zad/fJiexixgUqjtjD1L4zoLNP2f0INg==", + "license": "MIT" + }, + "node_modules/@alpinejs/persist": { +- "version": "3.17.3", +- "resolved": "https://registry.npmjs.org/@alpinejs/persist/-/persist-3.17.3.tgz", +- "integrity": "sha512-6Fm40qY3uIFoLEHd1jAolt3iUgdYGDqgW7N4W2hqBlJO4JMzMHAMzcN9weFBcMcwd9eQrO016Qvt3kryGu1abw==", ++ "version": "3.17.4", ++ "resolved": "https://registry.npmjs.org/@alpinejs/persist/-/persist-3.17.4.tgz", ++ "integrity": "sha512-ZTPF2eqYP0khAKrlQRD/dz/q1W4yWAnbwmd25NyMOQmFOD9839xP2+Go4zDp2w2jfSQPM4SL1nA5X0knUpSsTw==", + "license": "MIT" + }, + "node_modules/@alpinejs/resize": { +- "version": "3.17.3", +- "resolved": "https://registry.npmjs.org/@alpinejs/resize/-/resize-3.17.3.tgz", +- "integrity": "sha512-7FKc7a/yFHhd9ikX02Fu35+y+f4IgbUfL3Sy77ufHjzbEU3TXmvHPPmfsbCyJZBMXtNJfVPrck1LkC/pspwO/g==", ++ "version": "3.17.4", ++ "resolved": "https://registry.npmjs.org/@alpinejs/resize/-/resize-3.17.4.tgz", ++ "integrity": "sha512-IoWyu8o86JAm0HiGFu0bSUaNfFnNMJYtERm0E4s4TCVZ5x8t8cpOAMo62fuAMaLEaEeRCL4c9dmAuYDXzoAewA==", + "license": "MIT" + }, + "node_modules/@alpinejs/sort": { +- "version": "3.17.3", +- "resolved": "https://registry.npmjs.org/@alpinejs/sort/-/sort-3.17.3.tgz", +- "integrity": "sha512-Yq2PpXwnOrhb3wr+KkBbs/jB4WPFGm7S5O3i/okgeQjrw/q6KohP7Fdn5Q9Q9Az4DBeBc3EUg0161+g9KOr8Qg==", ++ "version": "3.17.4", ++ "resolved": "https://registry.npmjs.org/@alpinejs/sort/-/sort-3.17.4.tgz", ++ "integrity": "sha512-GHy/duQx9CvvDu9bUxDxFFwBVTZ59QQNQOEQ346h8qFqQU1lcK1vfxZTQWfw6hujCUJ+Xi2ayjXO7OvMb+NQRA==", + "license": "MIT", + "dependencies": { + "sortablejs": "^1.15.2" +@@ -1266,9 +1266,9 @@ + } + }, + "node_modules/alpinejs": { +- "version": "3.17.3", +- "resolved": "https://registry.npmjs.org/alpinejs/-/alpinejs-3.17.3.tgz", +- "integrity": "sha512-hIfoRTBBeHMeMu6gXuKwwNoY6pJ7bwpZ91dXVrqRhUhHFOyGr4S21sUYqbxPY5Cnjo0RAmPZVRRZw1becRyV0Q==", ++ "version": "3.17.4", ++ "resolved": "https://registry.npmjs.org/alpinejs/-/alpinejs-3.17.4.tgz", ++ "integrity": "sha512-N2gsr+58XVUt7OAPKnUGiKPDtkd+xbSGTae8C8IJxeRdkkhBJPIautkJ+qcwb7lcjJ/QK3/CPVIbN20JPvtK7A==", + "license": "MIT", + "dependencies": { + "@vue/reactivity": "~3.5.40" +diff --git a/package.json b/package.json +index cb068fe1..4cb964a3 100644 +--- a/package.json ++++ b/package.json +@@ -17,18 +17,18 @@ + "vitest": "^3.2.4" + }, + "dependencies": { +- "@alpinejs/anchor": "^3.17.3", +- "@alpinejs/collapse": "^3.17.3", +- "@alpinejs/csp": "^3.17.3", +- "@alpinejs/focus": "^3.17.3", +- "@alpinejs/intersect": "^3.17.3", +- "@alpinejs/mask": "^3.17.3", +- "@alpinejs/morph": "^3.17.3", +- "@alpinejs/persist": "^3.17.3", +- "@alpinejs/resize": "^3.17.3", +- "@alpinejs/sort": "^3.17.3", ++ "@alpinejs/anchor": "^3.17.4", ++ "@alpinejs/collapse": "^3.17.4", ++ "@alpinejs/csp": "^3.17.4", ++ "@alpinejs/focus": "^3.17.4", ++ "@alpinejs/intersect": "^3.17.4", ++ "@alpinejs/mask": "^3.17.4", ++ "@alpinejs/morph": "^3.17.4", ++ "@alpinejs/persist": "^3.17.4", ++ "@alpinejs/resize": "^3.17.4", ++ "@alpinejs/sort": "^3.17.4", + "@vue/reactivity": "^3.2.45", +- "alpinejs": "^3.17.3", ++ "alpinejs": "^3.17.4", + "nprogress": "^0.2.0" + } + } diff --git a/tasks/livewire__livewire-10730/solution/solve.sh b/tasks/livewire__livewire-10730/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/livewire__livewire-10730/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/livewire__livewire-10730/task.toml b/tasks/livewire__livewire-10730/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..47082937926f7845c65e8633bd37f91a3fa212f6 --- /dev/null +++ b/tasks/livewire__livewire-10730/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/livewire__livewire-10730" +description = "Update Alpine to v3.17.4 on main" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "livewire", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "livewire/livewire" +ref = "279ce07924bf1aa94e959864a433b38eee953176" +reference = "https://github.com/livewire/livewire/pull/10730" +source_access = "auto" +built_at = "2026-11-16T16:09:51.462338+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:616571c7e394da5ddd3a07490785006e0a5f38ce8a8235fce0183b86e0c9256b" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-21T17:52:21Z" +diff_format = "unified" +context_files = [ + "package-lock.json", + "package.json", +] +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.422088+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:96086fea51d5037272c371527ffb35cd7502ecf9222f07d400c41b4896ef6002" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/livewire__livewire-10730/tests/capture.py b/tasks/livewire__livewire-10730/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/livewire__livewire-10730/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/livewire__livewire-10730/tests/instruction.md b/tasks/livewire__livewire-10730/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..251eb2a84783e684e1e585dfe96ae72586ca5693 --- /dev/null +++ b/tasks/livewire__livewire-10730/tests/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** Update Alpine to v3.17.4 on main + +## Description + +Updates Alpine and all ten bundled plugin constraints to `^3.17.4`, then refreshes `package-lock.json` from the published npm registry artifacts. + +Verified all eleven lock entries resolve to v3.17.4 with registry URLs and integrity metadata. `npm ci`, the production build, and the JavaScript suite pass locally: 164 tests passed with one skipped. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `279ce07924bf`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10730/tests/oracle.patch b/tasks/livewire__livewire-10730/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..d3a39550935244745aabef9e67abde8f9424819d --- /dev/null +++ b/tasks/livewire__livewire-10730/tests/oracle.patch @@ -0,0 +1,185 @@ +diff --git a/package-lock.json b/package-lock.json +index dd397950..2862a828 100644 +--- a/package-lock.json ++++ b/package-lock.json +@@ -7,18 +7,18 @@ + "name": "laravel-livewire", + "license": "MIT", + "dependencies": { +- "@alpinejs/anchor": "^3.17.3", +- "@alpinejs/collapse": "^3.17.3", +- "@alpinejs/csp": "^3.17.3", +- "@alpinejs/focus": "^3.17.3", +- "@alpinejs/intersect": "^3.17.3", +- "@alpinejs/mask": "^3.17.3", +- "@alpinejs/morph": "^3.17.3", +- "@alpinejs/persist": "^3.17.3", +- "@alpinejs/resize": "^3.17.3", +- "@alpinejs/sort": "^3.17.3", ++ "@alpinejs/anchor": "^3.17.4", ++ "@alpinejs/collapse": "^3.17.4", ++ "@alpinejs/csp": "^3.17.4", ++ "@alpinejs/focus": "^3.17.4", ++ "@alpinejs/intersect": "^3.17.4", ++ "@alpinejs/mask": "^3.17.4", ++ "@alpinejs/morph": "^3.17.4", ++ "@alpinejs/persist": "^3.17.4", ++ "@alpinejs/resize": "^3.17.4", ++ "@alpinejs/sort": "^3.17.4", + "@vue/reactivity": "^3.2.45", +- "alpinejs": "^3.17.3", ++ "alpinejs": "^3.17.4", + "nprogress": "^0.2.0" + }, + "devDependencies": { +@@ -29,33 +29,33 @@ + } + }, + "node_modules/@alpinejs/anchor": { +- "version": "3.17.3", +- "resolved": "https://registry.npmjs.org/@alpinejs/anchor/-/anchor-3.17.3.tgz", +- "integrity": "sha512-BeKw+NCjkni6pya8jMZpPeL429L+qoSHIUs15LCbPF03bsANyWjUIC2jZ85PX+y6X9hjI1k4GQUIHwI/yRtWXw==", ++ "version": "3.17.4", ++ "resolved": "https://registry.npmjs.org/@alpinejs/anchor/-/anchor-3.17.4.tgz", ++ "integrity": "sha512-sHCML94TM7fugZucIJBb+vyw/igMdd3ZawGe/daoD1OIzTtJe0ShgFAzqG6Wj1gilZwV/HrI5P/OWovMSd76WQ==", + "license": "MIT", + "dependencies": { + "@floating-ui/dom": "^1.5.3" + } + }, + "node_modules/@alpinejs/collapse": { +- "version": "3.17.3", +- "resolved": "https://registry.npmjs.org/@alpinejs/collapse/-/collapse-3.17.3.tgz", +- "integrity": "sha512-pAROM7iHkwDtKmqWrWFII5/cOD4M/oTi3UyS0b8mNOLjIsNZ1YO32K+6rpwpuBfRAZgNxU0K1UntuLR9+p9Log==", ++ "version": "3.17.4", ++ "resolved": "https://registry.npmjs.org/@alpinejs/collapse/-/collapse-3.17.4.tgz", ++ "integrity": "sha512-Us4cE8jHzKtRs4mYNbmX4art/Hpm90vIGH6h5Mcv1EWK9Dgg48RNzSlPFt9F/D6bk2onbdeagYayqEvzpPbqPg==", + "license": "MIT" + }, + "node_modules/@alpinejs/csp": { +- "version": "3.17.3", +- "resolved": "https://registry.npmjs.org/@alpinejs/csp/-/csp-3.17.3.tgz", +- "integrity": "sha512-Y24sCNahmtdfSp4awWBRmdqHfWrZPfuoa++0YqI6BuEaZ/Xjn8BOuBOScO+fzCXK0V2Vo9Ryy9tWQnTIVMyObQ==", ++ "version": "3.17.4", ++ "resolved": "https://registry.npmjs.org/@alpinejs/csp/-/csp-3.17.4.tgz", ++ "integrity": "sha512-SlRXmqO6kYhnxlg+99etmuzJtE9Lk4QbKjBHqerXzaMflJqoJXdz/SI3IvHJGZ/vRVyC3bR0SSBz40oY7goBeg==", + "license": "MIT", + "dependencies": { + "@vue/reactivity": "~3.5.40" + } + }, + "node_modules/@alpinejs/focus": { +- "version": "3.17.3", +- "resolved": "https://registry.npmjs.org/@alpinejs/focus/-/focus-3.17.3.tgz", +- "integrity": "sha512-d91S3KiSnOyrMBfKsWoHKEw+ZPlVWHkaHBQgwPDOFgdVAxFsvZXEXi1EzX0QbOtLW9HqQwcFiqxoxRgs59UNyg==", ++ "version": "3.17.4", ++ "resolved": "https://registry.npmjs.org/@alpinejs/focus/-/focus-3.17.4.tgz", ++ "integrity": "sha512-IpZuMQC+nk9xEr9lfqzI+m7Pwti3dfiYhB4UrRIbO2KurezOM5HppYYXVtRQ1mD7L3R7rGtjAQksvWpCnk3lGw==", + "license": "MIT", + "dependencies": { + "focus-trap": "^8.0.0", +@@ -63,39 +63,39 @@ + } + }, + "node_modules/@alpinejs/intersect": { +- "version": "3.17.3", +- "resolved": "https://registry.npmjs.org/@alpinejs/intersect/-/intersect-3.17.3.tgz", +- "integrity": "sha512-uBlcZ5UnEPGVlGCdXHguPgwMiBZJqNA1vrIBvbP6qBjeYJx4nE4YlWQztXBTJgZbU5BtWKo9pGZbzvFOlX+T/Q==", ++ "version": "3.17.4", ++ "resolved": "https://registry.npmjs.org/@alpinejs/intersect/-/intersect-3.17.4.tgz", ++ "integrity": "sha512-soIfavWRHh1dEs05z6wkKtYf8i/ohIG1EDo51urbURj8HifVLV8hd4oCVEGlKwEwt6NXBZDhWMhKk9SM//JHtQ==", + "license": "MIT" + }, + "node_modules/@alpinejs/mask": { +- "version": "3.17.3", +- "resolved": "https://registry.npmjs.org/@alpinejs/mask/-/mask-3.17.3.tgz", +- "integrity": "sha512-u8CD0FnmCApoqcZEr/6lOnrZzh4noVbiI+nEGIqhc9rj8ZA7rCt+Gtr6WDSsf5Dg1thTIfe5ykDg/WseiZl64g==", ++ "version": "3.17.4", ++ "resolved": "https://registry.npmjs.org/@alpinejs/mask/-/mask-3.17.4.tgz", ++ "integrity": "sha512-eEcggxA8+TlpMYoioF43vhLuoInL8rlkPpAZmIWh4SRLJwZRaxCYrb8W+A3kyiRos7z8Bfj2FHwJmq+jejfKaw==", + "license": "MIT" + }, + "node_modules/@alpinejs/morph": { +- "version": "3.17.3", +- "resolved": "https://registry.npmjs.org/@alpinejs/morph/-/morph-3.17.3.tgz", +- "integrity": "sha512-1oW48NjXKjLLzg4o7avVbZMz/pd7/pvlVHNOtF15pxVf5VUUg8Jq5F0wN8+eSlmU+LxyF3XWOZDtOEwY8/O1Aw==", ++ "version": "3.17.4", ++ "resolved": "https://registry.npmjs.org/@alpinejs/morph/-/morph-3.17.4.tgz", ++ "integrity": "sha512-0jjisxp/ErYv3yRFIccViLgJa+BODm8aBBS/kUBp62+qd4rJ5c6mJ1zad/fJiexixgUqjtjD1L4zoLNP2f0INg==", + "license": "MIT" + }, + "node_modules/@alpinejs/persist": { +- "version": "3.17.3", +- "resolved": "https://registry.npmjs.org/@alpinejs/persist/-/persist-3.17.3.tgz", +- "integrity": "sha512-6Fm40qY3uIFoLEHd1jAolt3iUgdYGDqgW7N4W2hqBlJO4JMzMHAMzcN9weFBcMcwd9eQrO016Qvt3kryGu1abw==", ++ "version": "3.17.4", ++ "resolved": "https://registry.npmjs.org/@alpinejs/persist/-/persist-3.17.4.tgz", ++ "integrity": "sha512-ZTPF2eqYP0khAKrlQRD/dz/q1W4yWAnbwmd25NyMOQmFOD9839xP2+Go4zDp2w2jfSQPM4SL1nA5X0knUpSsTw==", + "license": "MIT" + }, + "node_modules/@alpinejs/resize": { +- "version": "3.17.3", +- "resolved": "https://registry.npmjs.org/@alpinejs/resize/-/resize-3.17.3.tgz", +- "integrity": "sha512-7FKc7a/yFHhd9ikX02Fu35+y+f4IgbUfL3Sy77ufHjzbEU3TXmvHPPmfsbCyJZBMXtNJfVPrck1LkC/pspwO/g==", ++ "version": "3.17.4", ++ "resolved": "https://registry.npmjs.org/@alpinejs/resize/-/resize-3.17.4.tgz", ++ "integrity": "sha512-IoWyu8o86JAm0HiGFu0bSUaNfFnNMJYtERm0E4s4TCVZ5x8t8cpOAMo62fuAMaLEaEeRCL4c9dmAuYDXzoAewA==", + "license": "MIT" + }, + "node_modules/@alpinejs/sort": { +- "version": "3.17.3", +- "resolved": "https://registry.npmjs.org/@alpinejs/sort/-/sort-3.17.3.tgz", +- "integrity": "sha512-Yq2PpXwnOrhb3wr+KkBbs/jB4WPFGm7S5O3i/okgeQjrw/q6KohP7Fdn5Q9Q9Az4DBeBc3EUg0161+g9KOr8Qg==", ++ "version": "3.17.4", ++ "resolved": "https://registry.npmjs.org/@alpinejs/sort/-/sort-3.17.4.tgz", ++ "integrity": "sha512-GHy/duQx9CvvDu9bUxDxFFwBVTZ59QQNQOEQ346h8qFqQU1lcK1vfxZTQWfw6hujCUJ+Xi2ayjXO7OvMb+NQRA==", + "license": "MIT", + "dependencies": { + "sortablejs": "^1.15.2" +@@ -1266,9 +1266,9 @@ + } + }, + "node_modules/alpinejs": { +- "version": "3.17.3", +- "resolved": "https://registry.npmjs.org/alpinejs/-/alpinejs-3.17.3.tgz", +- "integrity": "sha512-hIfoRTBBeHMeMu6gXuKwwNoY6pJ7bwpZ91dXVrqRhUhHFOyGr4S21sUYqbxPY5Cnjo0RAmPZVRRZw1becRyV0Q==", ++ "version": "3.17.4", ++ "resolved": "https://registry.npmjs.org/alpinejs/-/alpinejs-3.17.4.tgz", ++ "integrity": "sha512-N2gsr+58XVUt7OAPKnUGiKPDtkd+xbSGTae8C8IJxeRdkkhBJPIautkJ+qcwb7lcjJ/QK3/CPVIbN20JPvtK7A==", + "license": "MIT", + "dependencies": { + "@vue/reactivity": "~3.5.40" +diff --git a/package.json b/package.json +index cb068fe1..4cb964a3 100644 +--- a/package.json ++++ b/package.json +@@ -17,18 +17,18 @@ + "vitest": "^3.2.4" + }, + "dependencies": { +- "@alpinejs/anchor": "^3.17.3", +- "@alpinejs/collapse": "^3.17.3", +- "@alpinejs/csp": "^3.17.3", +- "@alpinejs/focus": "^3.17.3", +- "@alpinejs/intersect": "^3.17.3", +- "@alpinejs/mask": "^3.17.3", +- "@alpinejs/morph": "^3.17.3", +- "@alpinejs/persist": "^3.17.3", +- "@alpinejs/resize": "^3.17.3", +- "@alpinejs/sort": "^3.17.3", ++ "@alpinejs/anchor": "^3.17.4", ++ "@alpinejs/collapse": "^3.17.4", ++ "@alpinejs/csp": "^3.17.4", ++ "@alpinejs/focus": "^3.17.4", ++ "@alpinejs/intersect": "^3.17.4", ++ "@alpinejs/mask": "^3.17.4", ++ "@alpinejs/morph": "^3.17.4", ++ "@alpinejs/persist": "^3.17.4", ++ "@alpinejs/resize": "^3.17.4", ++ "@alpinejs/sort": "^3.17.4", + "@vue/reactivity": "^3.2.45", +- "alpinejs": "^3.17.3", ++ "alpinejs": "^3.17.4", + "nprogress": "^0.2.0" + } + } diff --git a/tasks/livewire__livewire-10730/tests/test.sh b/tasks/livewire__livewire-10730/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..5f2037f93040a96876e07813dbcddcd5597b9a7f --- /dev/null +++ b/tasks/livewire__livewire-10730/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 279ce07924bf1aa94e959864a433b38eee953176 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/livewire__livewire-10730/tests/verifier.py b/tasks/livewire__livewire-10730/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/livewire__livewire-10730/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/livewire__livewire-10731/environment/Dockerfile b/tasks/livewire__livewire-10731/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cab49ab3514b568f9d9335fd582e16901cd00d80 --- /dev/null +++ b/tasks/livewire__livewire-10731/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/livewire/livewire.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/livewire/livewire.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/livewire/livewire.git +WORKDIR /workspace +RUN git fetch --depth 1 origin c931d18efef13cde5f1e594ad884e709d1544c51 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard c931d18efef13cde5f1e594ad884e709d1544c51 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base c931d18efef13cde5f1e594ad884e709d1544c51 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/livewire__livewire-10731/instruction.md b/tasks/livewire__livewire-10731/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a9ab4efbfd94cf57e94cb1a39ecae47e09b631c2 --- /dev/null +++ b/tasks/livewire__livewire-10731/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** Update Alpine to v3.17.4 on 4.x + +## Description + +Updates Alpine and all ten bundled plugin constraints to `^3.17.4`, then refreshes `package-lock.json` from the published npm registry artifacts. + +Verified all eleven lock entries resolve to v3.17.4 with registry URLs and integrity metadata. `npm ci`, the production build, and the JavaScript suite pass locally: 110 tests passed with one skipped. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `c931d18efef1`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10731/solution/patch.diff b/tasks/livewire__livewire-10731/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..d8b46b6a3c2b569c4fbeffb17a8406add2163151 --- /dev/null +++ b/tasks/livewire__livewire-10731/solution/patch.diff @@ -0,0 +1,185 @@ +diff --git a/package-lock.json b/package-lock.json +index 8b0e1f48..bbd862ac 100644 +--- a/package-lock.json ++++ b/package-lock.json +@@ -7,18 +7,18 @@ + "name": "laravel-livewire", + "license": "MIT", + "dependencies": { +- "@alpinejs/anchor": "^3.17.3", +- "@alpinejs/collapse": "^3.17.3", +- "@alpinejs/csp": "^3.17.3", +- "@alpinejs/focus": "^3.17.3", +- "@alpinejs/intersect": "^3.17.3", +- "@alpinejs/mask": "^3.17.3", +- "@alpinejs/morph": "^3.17.3", +- "@alpinejs/persist": "^3.17.3", +- "@alpinejs/resize": "^3.17.3", +- "@alpinejs/sort": "^3.17.3", ++ "@alpinejs/anchor": "^3.17.4", ++ "@alpinejs/collapse": "^3.17.4", ++ "@alpinejs/csp": "^3.17.4", ++ "@alpinejs/focus": "^3.17.4", ++ "@alpinejs/intersect": "^3.17.4", ++ "@alpinejs/mask": "^3.17.4", ++ "@alpinejs/morph": "^3.17.4", ++ "@alpinejs/persist": "^3.17.4", ++ "@alpinejs/resize": "^3.17.4", ++ "@alpinejs/sort": "^3.17.4", + "@vue/reactivity": "^3.2.45", +- "alpinejs": "^3.17.3", ++ "alpinejs": "^3.17.4", + "nprogress": "^0.2.0" + }, + "devDependencies": { +@@ -29,33 +29,33 @@ + } + }, + "node_modules/@alpinejs/anchor": { +- "version": "3.17.3", +- "resolved": "https://registry.npmjs.org/@alpinejs/anchor/-/anchor-3.17.3.tgz", +- "integrity": "sha512-BeKw+NCjkni6pya8jMZpPeL429L+qoSHIUs15LCbPF03bsANyWjUIC2jZ85PX+y6X9hjI1k4GQUIHwI/yRtWXw==", ++ "version": "3.17.4", ++ "resolved": "https://registry.npmjs.org/@alpinejs/anchor/-/anchor-3.17.4.tgz", ++ "integrity": "sha512-sHCML94TM7fugZucIJBb+vyw/igMdd3ZawGe/daoD1OIzTtJe0ShgFAzqG6Wj1gilZwV/HrI5P/OWovMSd76WQ==", + "license": "MIT", + "dependencies": { + "@floating-ui/dom": "^1.5.3" + } + }, + "node_modules/@alpinejs/collapse": { +- "version": "3.17.3", +- "resolved": "https://registry.npmjs.org/@alpinejs/collapse/-/collapse-3.17.3.tgz", +- "integrity": "sha512-pAROM7iHkwDtKmqWrWFII5/cOD4M/oTi3UyS0b8mNOLjIsNZ1YO32K+6rpwpuBfRAZgNxU0K1UntuLR9+p9Log==", ++ "version": "3.17.4", ++ "resolved": "https://registry.npmjs.org/@alpinejs/collapse/-/collapse-3.17.4.tgz", ++ "integrity": "sha512-Us4cE8jHzKtRs4mYNbmX4art/Hpm90vIGH6h5Mcv1EWK9Dgg48RNzSlPFt9F/D6bk2onbdeagYayqEvzpPbqPg==", + "license": "MIT" + }, + "node_modules/@alpinejs/csp": { +- "version": "3.17.3", +- "resolved": "https://registry.npmjs.org/@alpinejs/csp/-/csp-3.17.3.tgz", +- "integrity": "sha512-Y24sCNahmtdfSp4awWBRmdqHfWrZPfuoa++0YqI6BuEaZ/Xjn8BOuBOScO+fzCXK0V2Vo9Ryy9tWQnTIVMyObQ==", ++ "version": "3.17.4", ++ "resolved": "https://registry.npmjs.org/@alpinejs/csp/-/csp-3.17.4.tgz", ++ "integrity": "sha512-SlRXmqO6kYhnxlg+99etmuzJtE9Lk4QbKjBHqerXzaMflJqoJXdz/SI3IvHJGZ/vRVyC3bR0SSBz40oY7goBeg==", + "license": "MIT", + "dependencies": { + "@vue/reactivity": "~3.5.40" + } + }, + "node_modules/@alpinejs/focus": { +- "version": "3.17.3", +- "resolved": "https://registry.npmjs.org/@alpinejs/focus/-/focus-3.17.3.tgz", +- "integrity": "sha512-d91S3KiSnOyrMBfKsWoHKEw+ZPlVWHkaHBQgwPDOFgdVAxFsvZXEXi1EzX0QbOtLW9HqQwcFiqxoxRgs59UNyg==", ++ "version": "3.17.4", ++ "resolved": "https://registry.npmjs.org/@alpinejs/focus/-/focus-3.17.4.tgz", ++ "integrity": "sha512-IpZuMQC+nk9xEr9lfqzI+m7Pwti3dfiYhB4UrRIbO2KurezOM5HppYYXVtRQ1mD7L3R7rGtjAQksvWpCnk3lGw==", + "license": "MIT", + "dependencies": { + "focus-trap": "^8.0.0", +@@ -63,39 +63,39 @@ + } + }, + "node_modules/@alpinejs/intersect": { +- "version": "3.17.3", +- "resolved": "https://registry.npmjs.org/@alpinejs/intersect/-/intersect-3.17.3.tgz", +- "integrity": "sha512-uBlcZ5UnEPGVlGCdXHguPgwMiBZJqNA1vrIBvbP6qBjeYJx4nE4YlWQztXBTJgZbU5BtWKo9pGZbzvFOlX+T/Q==", ++ "version": "3.17.4", ++ "resolved": "https://registry.npmjs.org/@alpinejs/intersect/-/intersect-3.17.4.tgz", ++ "integrity": "sha512-soIfavWRHh1dEs05z6wkKtYf8i/ohIG1EDo51urbURj8HifVLV8hd4oCVEGlKwEwt6NXBZDhWMhKk9SM//JHtQ==", + "license": "MIT" + }, + "node_modules/@alpinejs/mask": { +- "version": "3.17.3", +- "resolved": "https://registry.npmjs.org/@alpinejs/mask/-/mask-3.17.3.tgz", +- "integrity": "sha512-u8CD0FnmCApoqcZEr/6lOnrZzh4noVbiI+nEGIqhc9rj8ZA7rCt+Gtr6WDSsf5Dg1thTIfe5ykDg/WseiZl64g==", ++ "version": "3.17.4", ++ "resolved": "https://registry.npmjs.org/@alpinejs/mask/-/mask-3.17.4.tgz", ++ "integrity": "sha512-eEcggxA8+TlpMYoioF43vhLuoInL8rlkPpAZmIWh4SRLJwZRaxCYrb8W+A3kyiRos7z8Bfj2FHwJmq+jejfKaw==", + "license": "MIT" + }, + "node_modules/@alpinejs/morph": { +- "version": "3.17.3", +- "resolved": "https://registry.npmjs.org/@alpinejs/morph/-/morph-3.17.3.tgz", +- "integrity": "sha512-1oW48NjXKjLLzg4o7avVbZMz/pd7/pvlVHNOtF15pxVf5VUUg8Jq5F0wN8+eSlmU+LxyF3XWOZDtOEwY8/O1Aw==", ++ "version": "3.17.4", ++ "resolved": "https://registry.npmjs.org/@alpinejs/morph/-/morph-3.17.4.tgz", ++ "integrity": "sha512-0jjisxp/ErYv3yRFIccViLgJa+BODm8aBBS/kUBp62+qd4rJ5c6mJ1zad/fJiexixgUqjtjD1L4zoLNP2f0INg==", + "license": "MIT" + }, + "node_modules/@alpinejs/persist": { +- "version": "3.17.3", +- "resolved": "https://registry.npmjs.org/@alpinejs/persist/-/persist-3.17.3.tgz", +- "integrity": "sha512-6Fm40qY3uIFoLEHd1jAolt3iUgdYGDqgW7N4W2hqBlJO4JMzMHAMzcN9weFBcMcwd9eQrO016Qvt3kryGu1abw==", ++ "version": "3.17.4", ++ "resolved": "https://registry.npmjs.org/@alpinejs/persist/-/persist-3.17.4.tgz", ++ "integrity": "sha512-ZTPF2eqYP0khAKrlQRD/dz/q1W4yWAnbwmd25NyMOQmFOD9839xP2+Go4zDp2w2jfSQPM4SL1nA5X0knUpSsTw==", + "license": "MIT" + }, + "node_modules/@alpinejs/resize": { +- "version": "3.17.3", +- "resolved": "https://registry.npmjs.org/@alpinejs/resize/-/resize-3.17.3.tgz", +- "integrity": "sha512-7FKc7a/yFHhd9ikX02Fu35+y+f4IgbUfL3Sy77ufHjzbEU3TXmvHPPmfsbCyJZBMXtNJfVPrck1LkC/pspwO/g==", ++ "version": "3.17.4", ++ "resolved": "https://registry.npmjs.org/@alpinejs/resize/-/resize-3.17.4.tgz", ++ "integrity": "sha512-IoWyu8o86JAm0HiGFu0bSUaNfFnNMJYtERm0E4s4TCVZ5x8t8cpOAMo62fuAMaLEaEeRCL4c9dmAuYDXzoAewA==", + "license": "MIT" + }, + "node_modules/@alpinejs/sort": { +- "version": "3.17.3", +- "resolved": "https://registry.npmjs.org/@alpinejs/sort/-/sort-3.17.3.tgz", +- "integrity": "sha512-Yq2PpXwnOrhb3wr+KkBbs/jB4WPFGm7S5O3i/okgeQjrw/q6KohP7Fdn5Q9Q9Az4DBeBc3EUg0161+g9KOr8Qg==", ++ "version": "3.17.4", ++ "resolved": "https://registry.npmjs.org/@alpinejs/sort/-/sort-3.17.4.tgz", ++ "integrity": "sha512-GHy/duQx9CvvDu9bUxDxFFwBVTZ59QQNQOEQ346h8qFqQU1lcK1vfxZTQWfw6hujCUJ+Xi2ayjXO7OvMb+NQRA==", + "license": "MIT", + "dependencies": { + "sortablejs": "^1.15.2" +@@ -768,9 +768,9 @@ + } + }, + "node_modules/alpinejs": { +- "version": "3.17.3", +- "resolved": "https://registry.npmjs.org/alpinejs/-/alpinejs-3.17.3.tgz", +- "integrity": "sha512-hIfoRTBBeHMeMu6gXuKwwNoY6pJ7bwpZ91dXVrqRhUhHFOyGr4S21sUYqbxPY5Cnjo0RAmPZVRRZw1becRyV0Q==", ++ "version": "3.17.4", ++ "resolved": "https://registry.npmjs.org/alpinejs/-/alpinejs-3.17.4.tgz", ++ "integrity": "sha512-N2gsr+58XVUt7OAPKnUGiKPDtkd+xbSGTae8C8IJxeRdkkhBJPIautkJ+qcwb7lcjJ/QK3/CPVIbN20JPvtK7A==", + "license": "MIT", + "dependencies": { + "@vue/reactivity": "~3.5.40" +diff --git a/package.json b/package.json +index c26364e9..4dc5bf84 100644 +--- a/package.json ++++ b/package.json +@@ -17,18 +17,18 @@ + "vitest": "^4.1.11" + }, + "dependencies": { +- "@alpinejs/anchor": "^3.17.3", +- "@alpinejs/collapse": "^3.17.3", +- "@alpinejs/csp": "^3.17.3", +- "@alpinejs/focus": "^3.17.3", +- "@alpinejs/intersect": "^3.17.3", +- "@alpinejs/mask": "^3.17.3", +- "@alpinejs/morph": "^3.17.3", +- "@alpinejs/persist": "^3.17.3", +- "@alpinejs/resize": "^3.17.3", +- "@alpinejs/sort": "^3.17.3", ++ "@alpinejs/anchor": "^3.17.4", ++ "@alpinejs/collapse": "^3.17.4", ++ "@alpinejs/csp": "^3.17.4", ++ "@alpinejs/focus": "^3.17.4", ++ "@alpinejs/intersect": "^3.17.4", ++ "@alpinejs/mask": "^3.17.4", ++ "@alpinejs/morph": "^3.17.4", ++ "@alpinejs/persist": "^3.17.4", ++ "@alpinejs/resize": "^3.17.4", ++ "@alpinejs/sort": "^3.17.4", + "@vue/reactivity": "^3.2.45", +- "alpinejs": "^3.17.3", ++ "alpinejs": "^3.17.4", + "nprogress": "^0.2.0" + } + } diff --git a/tasks/livewire__livewire-10731/solution/solve.sh b/tasks/livewire__livewire-10731/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/livewire__livewire-10731/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/livewire__livewire-10731/task.toml b/tasks/livewire__livewire-10731/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ec05c9fc3cc80b6af9621fba983728f0e8a2b90c --- /dev/null +++ b/tasks/livewire__livewire-10731/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/livewire__livewire-10731" +description = "Update Alpine to v3.17.4 on 4.x" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "livewire", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "livewire/livewire" +ref = "c931d18efef13cde5f1e594ad884e709d1544c51" +reference = "https://github.com/livewire/livewire/pull/10731" +source_access = "auto" +built_at = "2026-11-16T16:09:51.460721+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:9b29ebb9213e646456a8b4887cf73d764cb5dc682d0d70502919b1e8284dabf4" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-21T17:52:30Z" +diff_format = "unified" +context_files = [ + "package-lock.json", + "package.json", +] +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.422559+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:30f336bf09d274e14c79be252b2223b755880503754946319f64e5bc77ac4d1e" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/livewire__livewire-10731/tests/capture.py b/tasks/livewire__livewire-10731/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/livewire__livewire-10731/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/livewire__livewire-10731/tests/instruction.md b/tasks/livewire__livewire-10731/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a9ab4efbfd94cf57e94cb1a39ecae47e09b631c2 --- /dev/null +++ b/tasks/livewire__livewire-10731/tests/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** Update Alpine to v3.17.4 on 4.x + +## Description + +Updates Alpine and all ten bundled plugin constraints to `^3.17.4`, then refreshes `package-lock.json` from the published npm registry artifacts. + +Verified all eleven lock entries resolve to v3.17.4 with registry URLs and integrity metadata. `npm ci`, the production build, and the JavaScript suite pass locally: 110 tests passed with one skipped. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `c931d18efef1`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10731/tests/oracle.patch b/tasks/livewire__livewire-10731/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..d8b46b6a3c2b569c4fbeffb17a8406add2163151 --- /dev/null +++ b/tasks/livewire__livewire-10731/tests/oracle.patch @@ -0,0 +1,185 @@ +diff --git a/package-lock.json b/package-lock.json +index 8b0e1f48..bbd862ac 100644 +--- a/package-lock.json ++++ b/package-lock.json +@@ -7,18 +7,18 @@ + "name": "laravel-livewire", + "license": "MIT", + "dependencies": { +- "@alpinejs/anchor": "^3.17.3", +- "@alpinejs/collapse": "^3.17.3", +- "@alpinejs/csp": "^3.17.3", +- "@alpinejs/focus": "^3.17.3", +- "@alpinejs/intersect": "^3.17.3", +- "@alpinejs/mask": "^3.17.3", +- "@alpinejs/morph": "^3.17.3", +- "@alpinejs/persist": "^3.17.3", +- "@alpinejs/resize": "^3.17.3", +- "@alpinejs/sort": "^3.17.3", ++ "@alpinejs/anchor": "^3.17.4", ++ "@alpinejs/collapse": "^3.17.4", ++ "@alpinejs/csp": "^3.17.4", ++ "@alpinejs/focus": "^3.17.4", ++ "@alpinejs/intersect": "^3.17.4", ++ "@alpinejs/mask": "^3.17.4", ++ "@alpinejs/morph": "^3.17.4", ++ "@alpinejs/persist": "^3.17.4", ++ "@alpinejs/resize": "^3.17.4", ++ "@alpinejs/sort": "^3.17.4", + "@vue/reactivity": "^3.2.45", +- "alpinejs": "^3.17.3", ++ "alpinejs": "^3.17.4", + "nprogress": "^0.2.0" + }, + "devDependencies": { +@@ -29,33 +29,33 @@ + } + }, + "node_modules/@alpinejs/anchor": { +- "version": "3.17.3", +- "resolved": "https://registry.npmjs.org/@alpinejs/anchor/-/anchor-3.17.3.tgz", +- "integrity": "sha512-BeKw+NCjkni6pya8jMZpPeL429L+qoSHIUs15LCbPF03bsANyWjUIC2jZ85PX+y6X9hjI1k4GQUIHwI/yRtWXw==", ++ "version": "3.17.4", ++ "resolved": "https://registry.npmjs.org/@alpinejs/anchor/-/anchor-3.17.4.tgz", ++ "integrity": "sha512-sHCML94TM7fugZucIJBb+vyw/igMdd3ZawGe/daoD1OIzTtJe0ShgFAzqG6Wj1gilZwV/HrI5P/OWovMSd76WQ==", + "license": "MIT", + "dependencies": { + "@floating-ui/dom": "^1.5.3" + } + }, + "node_modules/@alpinejs/collapse": { +- "version": "3.17.3", +- "resolved": "https://registry.npmjs.org/@alpinejs/collapse/-/collapse-3.17.3.tgz", +- "integrity": "sha512-pAROM7iHkwDtKmqWrWFII5/cOD4M/oTi3UyS0b8mNOLjIsNZ1YO32K+6rpwpuBfRAZgNxU0K1UntuLR9+p9Log==", ++ "version": "3.17.4", ++ "resolved": "https://registry.npmjs.org/@alpinejs/collapse/-/collapse-3.17.4.tgz", ++ "integrity": "sha512-Us4cE8jHzKtRs4mYNbmX4art/Hpm90vIGH6h5Mcv1EWK9Dgg48RNzSlPFt9F/D6bk2onbdeagYayqEvzpPbqPg==", + "license": "MIT" + }, + "node_modules/@alpinejs/csp": { +- "version": "3.17.3", +- "resolved": "https://registry.npmjs.org/@alpinejs/csp/-/csp-3.17.3.tgz", +- "integrity": "sha512-Y24sCNahmtdfSp4awWBRmdqHfWrZPfuoa++0YqI6BuEaZ/Xjn8BOuBOScO+fzCXK0V2Vo9Ryy9tWQnTIVMyObQ==", ++ "version": "3.17.4", ++ "resolved": "https://registry.npmjs.org/@alpinejs/csp/-/csp-3.17.4.tgz", ++ "integrity": "sha512-SlRXmqO6kYhnxlg+99etmuzJtE9Lk4QbKjBHqerXzaMflJqoJXdz/SI3IvHJGZ/vRVyC3bR0SSBz40oY7goBeg==", + "license": "MIT", + "dependencies": { + "@vue/reactivity": "~3.5.40" + } + }, + "node_modules/@alpinejs/focus": { +- "version": "3.17.3", +- "resolved": "https://registry.npmjs.org/@alpinejs/focus/-/focus-3.17.3.tgz", +- "integrity": "sha512-d91S3KiSnOyrMBfKsWoHKEw+ZPlVWHkaHBQgwPDOFgdVAxFsvZXEXi1EzX0QbOtLW9HqQwcFiqxoxRgs59UNyg==", ++ "version": "3.17.4", ++ "resolved": "https://registry.npmjs.org/@alpinejs/focus/-/focus-3.17.4.tgz", ++ "integrity": "sha512-IpZuMQC+nk9xEr9lfqzI+m7Pwti3dfiYhB4UrRIbO2KurezOM5HppYYXVtRQ1mD7L3R7rGtjAQksvWpCnk3lGw==", + "license": "MIT", + "dependencies": { + "focus-trap": "^8.0.0", +@@ -63,39 +63,39 @@ + } + }, + "node_modules/@alpinejs/intersect": { +- "version": "3.17.3", +- "resolved": "https://registry.npmjs.org/@alpinejs/intersect/-/intersect-3.17.3.tgz", +- "integrity": "sha512-uBlcZ5UnEPGVlGCdXHguPgwMiBZJqNA1vrIBvbP6qBjeYJx4nE4YlWQztXBTJgZbU5BtWKo9pGZbzvFOlX+T/Q==", ++ "version": "3.17.4", ++ "resolved": "https://registry.npmjs.org/@alpinejs/intersect/-/intersect-3.17.4.tgz", ++ "integrity": "sha512-soIfavWRHh1dEs05z6wkKtYf8i/ohIG1EDo51urbURj8HifVLV8hd4oCVEGlKwEwt6NXBZDhWMhKk9SM//JHtQ==", + "license": "MIT" + }, + "node_modules/@alpinejs/mask": { +- "version": "3.17.3", +- "resolved": "https://registry.npmjs.org/@alpinejs/mask/-/mask-3.17.3.tgz", +- "integrity": "sha512-u8CD0FnmCApoqcZEr/6lOnrZzh4noVbiI+nEGIqhc9rj8ZA7rCt+Gtr6WDSsf5Dg1thTIfe5ykDg/WseiZl64g==", ++ "version": "3.17.4", ++ "resolved": "https://registry.npmjs.org/@alpinejs/mask/-/mask-3.17.4.tgz", ++ "integrity": "sha512-eEcggxA8+TlpMYoioF43vhLuoInL8rlkPpAZmIWh4SRLJwZRaxCYrb8W+A3kyiRos7z8Bfj2FHwJmq+jejfKaw==", + "license": "MIT" + }, + "node_modules/@alpinejs/morph": { +- "version": "3.17.3", +- "resolved": "https://registry.npmjs.org/@alpinejs/morph/-/morph-3.17.3.tgz", +- "integrity": "sha512-1oW48NjXKjLLzg4o7avVbZMz/pd7/pvlVHNOtF15pxVf5VUUg8Jq5F0wN8+eSlmU+LxyF3XWOZDtOEwY8/O1Aw==", ++ "version": "3.17.4", ++ "resolved": "https://registry.npmjs.org/@alpinejs/morph/-/morph-3.17.4.tgz", ++ "integrity": "sha512-0jjisxp/ErYv3yRFIccViLgJa+BODm8aBBS/kUBp62+qd4rJ5c6mJ1zad/fJiexixgUqjtjD1L4zoLNP2f0INg==", + "license": "MIT" + }, + "node_modules/@alpinejs/persist": { +- "version": "3.17.3", +- "resolved": "https://registry.npmjs.org/@alpinejs/persist/-/persist-3.17.3.tgz", +- "integrity": "sha512-6Fm40qY3uIFoLEHd1jAolt3iUgdYGDqgW7N4W2hqBlJO4JMzMHAMzcN9weFBcMcwd9eQrO016Qvt3kryGu1abw==", ++ "version": "3.17.4", ++ "resolved": "https://registry.npmjs.org/@alpinejs/persist/-/persist-3.17.4.tgz", ++ "integrity": "sha512-ZTPF2eqYP0khAKrlQRD/dz/q1W4yWAnbwmd25NyMOQmFOD9839xP2+Go4zDp2w2jfSQPM4SL1nA5X0knUpSsTw==", + "license": "MIT" + }, + "node_modules/@alpinejs/resize": { +- "version": "3.17.3", +- "resolved": "https://registry.npmjs.org/@alpinejs/resize/-/resize-3.17.3.tgz", +- "integrity": "sha512-7FKc7a/yFHhd9ikX02Fu35+y+f4IgbUfL3Sy77ufHjzbEU3TXmvHPPmfsbCyJZBMXtNJfVPrck1LkC/pspwO/g==", ++ "version": "3.17.4", ++ "resolved": "https://registry.npmjs.org/@alpinejs/resize/-/resize-3.17.4.tgz", ++ "integrity": "sha512-IoWyu8o86JAm0HiGFu0bSUaNfFnNMJYtERm0E4s4TCVZ5x8t8cpOAMo62fuAMaLEaEeRCL4c9dmAuYDXzoAewA==", + "license": "MIT" + }, + "node_modules/@alpinejs/sort": { +- "version": "3.17.3", +- "resolved": "https://registry.npmjs.org/@alpinejs/sort/-/sort-3.17.3.tgz", +- "integrity": "sha512-Yq2PpXwnOrhb3wr+KkBbs/jB4WPFGm7S5O3i/okgeQjrw/q6KohP7Fdn5Q9Q9Az4DBeBc3EUg0161+g9KOr8Qg==", ++ "version": "3.17.4", ++ "resolved": "https://registry.npmjs.org/@alpinejs/sort/-/sort-3.17.4.tgz", ++ "integrity": "sha512-GHy/duQx9CvvDu9bUxDxFFwBVTZ59QQNQOEQ346h8qFqQU1lcK1vfxZTQWfw6hujCUJ+Xi2ayjXO7OvMb+NQRA==", + "license": "MIT", + "dependencies": { + "sortablejs": "^1.15.2" +@@ -768,9 +768,9 @@ + } + }, + "node_modules/alpinejs": { +- "version": "3.17.3", +- "resolved": "https://registry.npmjs.org/alpinejs/-/alpinejs-3.17.3.tgz", +- "integrity": "sha512-hIfoRTBBeHMeMu6gXuKwwNoY6pJ7bwpZ91dXVrqRhUhHFOyGr4S21sUYqbxPY5Cnjo0RAmPZVRRZw1becRyV0Q==", ++ "version": "3.17.4", ++ "resolved": "https://registry.npmjs.org/alpinejs/-/alpinejs-3.17.4.tgz", ++ "integrity": "sha512-N2gsr+58XVUt7OAPKnUGiKPDtkd+xbSGTae8C8IJxeRdkkhBJPIautkJ+qcwb7lcjJ/QK3/CPVIbN20JPvtK7A==", + "license": "MIT", + "dependencies": { + "@vue/reactivity": "~3.5.40" +diff --git a/package.json b/package.json +index c26364e9..4dc5bf84 100644 +--- a/package.json ++++ b/package.json +@@ -17,18 +17,18 @@ + "vitest": "^4.1.11" + }, + "dependencies": { +- "@alpinejs/anchor": "^3.17.3", +- "@alpinejs/collapse": "^3.17.3", +- "@alpinejs/csp": "^3.17.3", +- "@alpinejs/focus": "^3.17.3", +- "@alpinejs/intersect": "^3.17.3", +- "@alpinejs/mask": "^3.17.3", +- "@alpinejs/morph": "^3.17.3", +- "@alpinejs/persist": "^3.17.3", +- "@alpinejs/resize": "^3.17.3", +- "@alpinejs/sort": "^3.17.3", ++ "@alpinejs/anchor": "^3.17.4", ++ "@alpinejs/collapse": "^3.17.4", ++ "@alpinejs/csp": "^3.17.4", ++ "@alpinejs/focus": "^3.17.4", ++ "@alpinejs/intersect": "^3.17.4", ++ "@alpinejs/mask": "^3.17.4", ++ "@alpinejs/morph": "^3.17.4", ++ "@alpinejs/persist": "^3.17.4", ++ "@alpinejs/resize": "^3.17.4", ++ "@alpinejs/sort": "^3.17.4", + "@vue/reactivity": "^3.2.45", +- "alpinejs": "^3.17.3", ++ "alpinejs": "^3.17.4", + "nprogress": "^0.2.0" + } + } diff --git a/tasks/livewire__livewire-10731/tests/test.sh b/tasks/livewire__livewire-10731/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..69dce3f433d733afea610ba1ac852686eea4d4c8 --- /dev/null +++ b/tasks/livewire__livewire-10731/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace c931d18efef13cde5f1e594ad884e709d1544c51 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/livewire__livewire-10731/tests/verifier.py b/tasks/livewire__livewire-10731/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/livewire__livewire-10731/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/livewire__livewire-10732/environment/Dockerfile b/tasks/livewire__livewire-10732/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..4caeb68e48d79b778ef576d83ae40a9c8f86983c --- /dev/null +++ b/tasks/livewire__livewire-10732/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/livewire/livewire.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/livewire/livewire.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/livewire/livewire.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 279ce07924bf1aa94e959864a433b38eee953176 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 279ce07924bf1aa94e959864a433b38eee953176 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 279ce07924bf1aa94e959864a433b38eee953176 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/livewire__livewire-10732/instruction.md b/tasks/livewire__livewire-10732/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..bfc09b0c3cccaa17604db45aa4814b3b8a8fa54e --- /dev/null +++ b/tasks/livewire__livewire-10732/instruction.md @@ -0,0 +1,15 @@ +# Issue + +**Title:** Upmerge missing-method reporting fix to main + +## Description + +Carries the compatible 4.x fix from #10690 to main. + +In production, missing component methods return a generic 419 without being reported; debug mode retains the full exception. + +Verification: `php vendor/bin/phpunit src/Mechanisms/HandleComponents/UnitTest.php` passes 16 tests / 30 assertions. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `279ce07924bf`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10732/solution/patch.diff b/tasks/livewire__livewire-10732/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..dd58e047c31c2911f961bc1361dd6c3a83d77d2b --- /dev/null +++ b/tasks/livewire__livewire-10732/solution/patch.diff @@ -0,0 +1,113 @@ +diff --git a/src/Exceptions/MethodNotFoundException.php b/src/Exceptions/MethodNotFoundException.php +index 964ff8fe..2bd2abc2 100644 +--- a/src/Exceptions/MethodNotFoundException.php ++++ b/src/Exceptions/MethodNotFoundException.php +@@ -12,4 +12,18 @@ class MethodNotFoundException extends \Exception + "Unable to call component method. Public method [{$method}] not found on component" + ); + } ++ ++ public function report(): bool ++ { ++ return ! config('app.debug'); ++ } ++ ++ // In debug mode, let Laravel render the full error page. ++ // In production, return a generic 419 to avoid leaking details. ++ public function render($request) ++ { ++ if (config('app.debug')) return false; ++ ++ return response('', 419); ++ } + } +diff --git a/src/Mechanisms/HandleComponents/UnitTest.php b/src/Mechanisms/HandleComponents/UnitTest.php +index 456c0a66..e82bce6f 100644 +--- a/src/Mechanisms/HandleComponents/UnitTest.php ++++ b/src/Mechanisms/HandleComponents/UnitTest.php +@@ -2,12 +2,15 @@ + + namespace Livewire\Mechanisms\HandleComponents; + ++use Illuminate\Contracts\Debug\ExceptionHandler; + use Illuminate\Support\Carbon; + use Illuminate\Support\Facades\Route; + use Illuminate\Support\Stringable; + use Livewire\Component; ++use Livewire\Exceptions\MethodNotFoundException; + use Livewire\Form; + use Livewire\Livewire; ++use Livewire\Mechanisms\HandleRequests\EndpointResolver; + use Tests\TestComponent; + + class UnitTest extends \Tests\TestCase +@@ -267,6 +270,69 @@ class UnitTest extends \Tests\TestCase + ->call('refresh') + ->assertSetStrict('refreshed', true); + } ++ ++ public function test_invalid_call_method_name_returns_419_when_debug_is_disabled() ++ { ++ config()->set('app.debug', false); ++ ++ $component = Livewire::test(TestComponent::class); ++ ++ $response = $this->withHeaders(['X-Livewire' => 'true']) ++ ->postJson(EndpointResolver::updatePath(), ['components' => [ ++ [ ++ 'snapshot' => json_encode($component->snapshot), ++ 'updates' => [], ++ 'calls' => [ ++ ['method' => '|', 'params' => [], 'metadata' => []], ++ ], ++ ], ++ ]]); ++ ++ $response->assertStatus(419); ++ } ++ ++ public function test_method_not_found_exception_is_not_reported_when_debug_is_disabled() ++ { ++ config()->set('app.debug', false); ++ ++ $reported = []; ++ app(ExceptionHandler::class) ++ ->reportable(function (MethodNotFoundException $e) use (&$reported) { ++ $reported[] = $e; ++ ++ return false; ++ }); ++ ++ app(ExceptionHandler::class)->report(new MethodNotFoundException('invalidAction')); ++ ++ $this->assertEmpty($reported); ++ } ++ ++ public function test_invalid_call_method_name_throws_method_not_found_when_debug_is_enabled() ++ { ++ config()->set('app.debug', true); ++ ++ $this->expectException(MethodNotFoundException::class); ++ ++ Livewire::test(TestComponent::class)->call('missingAction'); ++ } ++ ++ public function test_method_not_found_exception_is_reported_when_debug_is_enabled() ++ { ++ config()->set('app.debug', true); ++ ++ $reported = []; ++ app(ExceptionHandler::class) ++ ->reportable(function (MethodNotFoundException $e) use (&$reported) { ++ $reported[] = $e; ++ ++ return false; ++ }); ++ ++ app(ExceptionHandler::class)->report(new MethodNotFoundException('invalidAction')); ++ ++ $this->assertCount(1, $reported); ++ } + } + + class BasicComponent extends TestComponent diff --git a/tasks/livewire__livewire-10732/solution/solve.sh b/tasks/livewire__livewire-10732/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/livewire__livewire-10732/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/livewire__livewire-10732/task.toml b/tasks/livewire__livewire-10732/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f597f74d53fe4948b96d46a074f155fc496fd73a --- /dev/null +++ b/tasks/livewire__livewire-10732/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/livewire__livewire-10732" +description = "Upmerge missing-method reporting fix to main" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "livewire", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "livewire/livewire" +ref = "279ce07924bf1aa94e959864a433b38eee953176" +reference = "https://github.com/livewire/livewire/pull/10732" +source_access = "auto" +built_at = "2026-11-16T16:09:51.463883+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:670c8d0fe4041a82541e9e2ab9cde373b4108a64534184fd12a80ce6b0a85d1d" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-21T17:52:09Z" +diff_format = "unified" +context_files = [ + "src/Exceptions/MethodNotFoundException.php", + "src/Mechanisms/HandleComponents/UnitTest.php", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 80 +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.423046+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:96086fea51d5037272c371527ffb35cd7502ecf9222f07d400c41b4896ef6002" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/livewire__livewire-10732/tests/capture.py b/tasks/livewire__livewire-10732/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/livewire__livewire-10732/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/livewire__livewire-10732/tests/instruction.md b/tasks/livewire__livewire-10732/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..bfc09b0c3cccaa17604db45aa4814b3b8a8fa54e --- /dev/null +++ b/tasks/livewire__livewire-10732/tests/instruction.md @@ -0,0 +1,15 @@ +# Issue + +**Title:** Upmerge missing-method reporting fix to main + +## Description + +Carries the compatible 4.x fix from #10690 to main. + +In production, missing component methods return a generic 419 without being reported; debug mode retains the full exception. + +Verification: `php vendor/bin/phpunit src/Mechanisms/HandleComponents/UnitTest.php` passes 16 tests / 30 assertions. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `279ce07924bf`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10732/tests/oracle.patch b/tasks/livewire__livewire-10732/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..dd58e047c31c2911f961bc1361dd6c3a83d77d2b --- /dev/null +++ b/tasks/livewire__livewire-10732/tests/oracle.patch @@ -0,0 +1,113 @@ +diff --git a/src/Exceptions/MethodNotFoundException.php b/src/Exceptions/MethodNotFoundException.php +index 964ff8fe..2bd2abc2 100644 +--- a/src/Exceptions/MethodNotFoundException.php ++++ b/src/Exceptions/MethodNotFoundException.php +@@ -12,4 +12,18 @@ class MethodNotFoundException extends \Exception + "Unable to call component method. Public method [{$method}] not found on component" + ); + } ++ ++ public function report(): bool ++ { ++ return ! config('app.debug'); ++ } ++ ++ // In debug mode, let Laravel render the full error page. ++ // In production, return a generic 419 to avoid leaking details. ++ public function render($request) ++ { ++ if (config('app.debug')) return false; ++ ++ return response('', 419); ++ } + } +diff --git a/src/Mechanisms/HandleComponents/UnitTest.php b/src/Mechanisms/HandleComponents/UnitTest.php +index 456c0a66..e82bce6f 100644 +--- a/src/Mechanisms/HandleComponents/UnitTest.php ++++ b/src/Mechanisms/HandleComponents/UnitTest.php +@@ -2,12 +2,15 @@ + + namespace Livewire\Mechanisms\HandleComponents; + ++use Illuminate\Contracts\Debug\ExceptionHandler; + use Illuminate\Support\Carbon; + use Illuminate\Support\Facades\Route; + use Illuminate\Support\Stringable; + use Livewire\Component; ++use Livewire\Exceptions\MethodNotFoundException; + use Livewire\Form; + use Livewire\Livewire; ++use Livewire\Mechanisms\HandleRequests\EndpointResolver; + use Tests\TestComponent; + + class UnitTest extends \Tests\TestCase +@@ -267,6 +270,69 @@ class UnitTest extends \Tests\TestCase + ->call('refresh') + ->assertSetStrict('refreshed', true); + } ++ ++ public function test_invalid_call_method_name_returns_419_when_debug_is_disabled() ++ { ++ config()->set('app.debug', false); ++ ++ $component = Livewire::test(TestComponent::class); ++ ++ $response = $this->withHeaders(['X-Livewire' => 'true']) ++ ->postJson(EndpointResolver::updatePath(), ['components' => [ ++ [ ++ 'snapshot' => json_encode($component->snapshot), ++ 'updates' => [], ++ 'calls' => [ ++ ['method' => '|', 'params' => [], 'metadata' => []], ++ ], ++ ], ++ ]]); ++ ++ $response->assertStatus(419); ++ } ++ ++ public function test_method_not_found_exception_is_not_reported_when_debug_is_disabled() ++ { ++ config()->set('app.debug', false); ++ ++ $reported = []; ++ app(ExceptionHandler::class) ++ ->reportable(function (MethodNotFoundException $e) use (&$reported) { ++ $reported[] = $e; ++ ++ return false; ++ }); ++ ++ app(ExceptionHandler::class)->report(new MethodNotFoundException('invalidAction')); ++ ++ $this->assertEmpty($reported); ++ } ++ ++ public function test_invalid_call_method_name_throws_method_not_found_when_debug_is_enabled() ++ { ++ config()->set('app.debug', true); ++ ++ $this->expectException(MethodNotFoundException::class); ++ ++ Livewire::test(TestComponent::class)->call('missingAction'); ++ } ++ ++ public function test_method_not_found_exception_is_reported_when_debug_is_enabled() ++ { ++ config()->set('app.debug', true); ++ ++ $reported = []; ++ app(ExceptionHandler::class) ++ ->reportable(function (MethodNotFoundException $e) use (&$reported) { ++ $reported[] = $e; ++ ++ return false; ++ }); ++ ++ app(ExceptionHandler::class)->report(new MethodNotFoundException('invalidAction')); ++ ++ $this->assertCount(1, $reported); ++ } + } + + class BasicComponent extends TestComponent diff --git a/tasks/livewire__livewire-10732/tests/test.sh b/tasks/livewire__livewire-10732/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..5f2037f93040a96876e07813dbcddcd5597b9a7f --- /dev/null +++ b/tasks/livewire__livewire-10732/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 279ce07924bf1aa94e959864a433b38eee953176 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/livewire__livewire-10732/tests/verifier.py b/tasks/livewire__livewire-10732/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/livewire__livewire-10732/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/livewire__livewire-10735/environment/Dockerfile b/tasks/livewire__livewire-10735/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d5e15b8911f04d7996146cf588c1f3720a1169be --- /dev/null +++ b/tasks/livewire__livewire-10735/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/livewire/livewire.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/livewire/livewire.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/livewire/livewire.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 9c6c728bf202a4b56be1d2b823eabaeb28609e41 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 9c6c728bf202a4b56be1d2b823eabaeb28609e41 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 9c6c728bf202a4b56be1d2b823eabaeb28609e41 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/livewire__livewire-10735/instruction.md b/tasks/livewire__livewire-10735/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8de96594975dfcb0d74b1e6be5a5b98b3b60854e --- /dev/null +++ b/tasks/livewire__livewire-10735/instruction.md @@ -0,0 +1,19 @@ +# Issue + +**Title:** Stabilize cross-version release CI tests + +## Description + +Fixes the two unit failures exposed by the post-merge `main` matrix. + +- Throw a real `ModelNotFoundException` directly so the status-code coverage works on Laravel 10, where `Eloquent\Collection::findOrFail()` is unavailable. +- Use `assertDontSeeText()` for layout content so a random Livewire component ID containing `bar` cannot fail the assertion. + +Verification: +- status-code test file: 8 tests / 10 assertions +- optional-layout test: 5 repeated passes +- complete Laravel 13 / PHP 8.4 Unit suite: 1,611 tests / 4,528 assertions, 13 skipped, 3 incomplete + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `9c6c728bf202`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10735/solution/patch.diff b/tasks/livewire__livewire-10735/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..f4248f906c5af7cc765a616835c037afbaf2570f --- /dev/null +++ b/tasks/livewire__livewire-10735/solution/patch.diff @@ -0,0 +1,34 @@ +diff --git a/src/Features/SupportPageComponents/UnitTest.php b/src/Features/SupportPageComponents/UnitTest.php +index a1fe2d47..71fda134 100644 +--- a/src/Features/SupportPageComponents/UnitTest.php ++++ b/src/Features/SupportPageComponents/UnitTest.php +@@ -138,7 +138,7 @@ class UnitTest extends \Tests\TestCase + $this + ->get('/configurable-layout') + ->assertSee('foo') +- ->assertDontSee('bar') ++ ->assertDontSeeText('bar') + ->assertSee('baz'); + } + +diff --git a/src/Features/SupportTesting/Tests/TestableLivewireCanAssertStatusCodesUnitTest.php b/src/Features/SupportTesting/Tests/TestableLivewireCanAssertStatusCodesUnitTest.php +index 30f5eddc..cfe2df69 100644 +--- a/src/Features/SupportTesting/Tests/TestableLivewireCanAssertStatusCodesUnitTest.php ++++ b/src/Features/SupportTesting/Tests/TestableLivewireCanAssertStatusCodesUnitTest.php +@@ -4,7 +4,6 @@ namespace Livewire\Features\SupportTesting\Tests; + + use Symfony\Component\HttpKernel\Exception\HttpException; + use Illuminate\Database\Eloquent\ModelNotFoundException; +-use Illuminate\Database\Eloquent\Collection; + use Livewire\Component; + use Livewire\Livewire; + use Tests\TestComponent; +@@ -82,7 +81,7 @@ class MissingModelComponent extends TestComponent + { + public function showFullDetails($id) + { +- (new Collection)->findOrFail($id); ++ throw (new ModelNotFoundException)->setModel('Post', [$id]); + } + } + diff --git a/tasks/livewire__livewire-10735/solution/solve.sh b/tasks/livewire__livewire-10735/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/livewire__livewire-10735/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/livewire__livewire-10735/task.toml b/tasks/livewire__livewire-10735/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..e99816f6275c62d6337437824433ba913ef3c285 --- /dev/null +++ b/tasks/livewire__livewire-10735/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/livewire__livewire-10735" +description = "Stabilize cross-version release CI tests" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "livewire", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "livewire/livewire" +ref = "9c6c728bf202a4b56be1d2b823eabaeb28609e41" +reference = "https://github.com/livewire/livewire/pull/10735" +source_access = "auto" +built_at = "2026-11-16T16:09:51.459256+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:8502f10c14f7f6b4de824a3bae9e3070f141530d2ecf74cc6b67c44cdba24af3" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-21T18:35:02Z" +diff_format = "unified" +context_files = [ + "src/Features/SupportPageComponents/UnitTest.php", + "src/Features/SupportTesting/Tests/TestableLivewireCanAssertStatusCodesUnitTest.php", +] +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.423570+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:5b3a0e8e867c3ed677c3c8c27a04a2297d23764ea4e42abd05f816efe9575522" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/livewire__livewire-10735/tests/capture.py b/tasks/livewire__livewire-10735/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/livewire__livewire-10735/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/livewire__livewire-10735/tests/instruction.md b/tasks/livewire__livewire-10735/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8de96594975dfcb0d74b1e6be5a5b98b3b60854e --- /dev/null +++ b/tasks/livewire__livewire-10735/tests/instruction.md @@ -0,0 +1,19 @@ +# Issue + +**Title:** Stabilize cross-version release CI tests + +## Description + +Fixes the two unit failures exposed by the post-merge `main` matrix. + +- Throw a real `ModelNotFoundException` directly so the status-code coverage works on Laravel 10, where `Eloquent\Collection::findOrFail()` is unavailable. +- Use `assertDontSeeText()` for layout content so a random Livewire component ID containing `bar` cannot fail the assertion. + +Verification: +- status-code test file: 8 tests / 10 assertions +- optional-layout test: 5 repeated passes +- complete Laravel 13 / PHP 8.4 Unit suite: 1,611 tests / 4,528 assertions, 13 skipped, 3 incomplete + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `9c6c728bf202`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10735/tests/oracle.patch b/tasks/livewire__livewire-10735/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..f4248f906c5af7cc765a616835c037afbaf2570f --- /dev/null +++ b/tasks/livewire__livewire-10735/tests/oracle.patch @@ -0,0 +1,34 @@ +diff --git a/src/Features/SupportPageComponents/UnitTest.php b/src/Features/SupportPageComponents/UnitTest.php +index a1fe2d47..71fda134 100644 +--- a/src/Features/SupportPageComponents/UnitTest.php ++++ b/src/Features/SupportPageComponents/UnitTest.php +@@ -138,7 +138,7 @@ class UnitTest extends \Tests\TestCase + $this + ->get('/configurable-layout') + ->assertSee('foo') +- ->assertDontSee('bar') ++ ->assertDontSeeText('bar') + ->assertSee('baz'); + } + +diff --git a/src/Features/SupportTesting/Tests/TestableLivewireCanAssertStatusCodesUnitTest.php b/src/Features/SupportTesting/Tests/TestableLivewireCanAssertStatusCodesUnitTest.php +index 30f5eddc..cfe2df69 100644 +--- a/src/Features/SupportTesting/Tests/TestableLivewireCanAssertStatusCodesUnitTest.php ++++ b/src/Features/SupportTesting/Tests/TestableLivewireCanAssertStatusCodesUnitTest.php +@@ -4,7 +4,6 @@ namespace Livewire\Features\SupportTesting\Tests; + + use Symfony\Component\HttpKernel\Exception\HttpException; + use Illuminate\Database\Eloquent\ModelNotFoundException; +-use Illuminate\Database\Eloquent\Collection; + use Livewire\Component; + use Livewire\Livewire; + use Tests\TestComponent; +@@ -82,7 +81,7 @@ class MissingModelComponent extends TestComponent + { + public function showFullDetails($id) + { +- (new Collection)->findOrFail($id); ++ throw (new ModelNotFoundException)->setModel('Post', [$id]); + } + } + diff --git a/tasks/livewire__livewire-10735/tests/test.sh b/tasks/livewire__livewire-10735/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..336febccbce83b726a390c9447fa6ab13c173809 --- /dev/null +++ b/tasks/livewire__livewire-10735/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 9c6c728bf202a4b56be1d2b823eabaeb28609e41 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/livewire__livewire-10735/tests/verifier.py b/tasks/livewire__livewire-10735/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/livewire__livewire-10735/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/livewire__livewire-10736/environment/Dockerfile b/tasks/livewire__livewire-10736/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2b0e159ee8ce195ce98a086105e83d9d0bd84fd4 --- /dev/null +++ b/tasks/livewire__livewire-10736/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/livewire/livewire.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/livewire/livewire.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/livewire/livewire.git +WORKDIR /workspace +RUN git fetch --depth 1 origin d0b4e22841d362dd213ee9602c399594d387b6ee 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard d0b4e22841d362dd213ee9602c399594d387b6ee \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base d0b4e22841d362dd213ee9602c399594d387b6ee \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/livewire__livewire-10736/instruction.md b/tasks/livewire__livewire-10736/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d63786c4f658791835689cfbf8c86262cc611c0f --- /dev/null +++ b/tasks/livewire__livewire-10736/instruction.md @@ -0,0 +1,28 @@ +# Issue + +**Title:** [4.x] Fix wildcard `validateOnly()` validating untargeted sibling keys + +## Description + +When `validateOnly()` is given a field with a wildcard followed by a specific key, sibling keys in every item after the first get validated too: + +```php +public $sections = [ + ['lines' => [['product' => 'Widget'], ['product' => '']]], + ['lines' => [['product' => 'Gadget'], ['product' => '']]], +]; + +$this->validateOnly('sections.*.lines.0.product', [ + 'sections.*.lines.*.product' => 'required', +]); + +// Fails on sections.1.lines.1.product, which was never targeted. +``` + +`filterCollectionDataDownToSpecificKeys()` passes the same `$ruleKeys` / `$fieldKeys` collections into the recursive call for every item, and each call `shift()`s them. The first item consumes the remaining path, so later items are left unfiltered. + +This PR passes each item its own copy of the remaining keys, so every item is filtered the same way. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d0b4e22841d3`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10736/solution/patch.diff b/tasks/livewire__livewire-10736/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..19e2afa5680e23970b697b8abeb5fc41a7dfc390 --- /dev/null +++ b/tasks/livewire__livewire-10736/solution/patch.diff @@ -0,0 +1,44 @@ +diff --git a/src/Features/SupportValidation/HandlesValidation.php b/src/Features/SupportValidation/HandlesValidation.php +index 8bcd4d08..a0f1f6f5 100644 +--- a/src/Features/SupportValidation/HandlesValidation.php ++++ b/src/Features/SupportValidation/HandlesValidation.php +@@ -437,7 +437,7 @@ trait HandlesValidation + if ($fieldKey == '*') { + // If the specified field has a '*', then loop through the collection and keep the whole collection intact. + foreach ($data as $key => $value) { +- $data[$key] = $this->filterCollectionDataDownToSpecificKeys($value, $ruleKeys, $fieldKeys); ++ $data[$key] = $this->filterCollectionDataDownToSpecificKeys($value, clone $ruleKeys, clone $fieldKeys); + } + } else { + // Otherwise filter collection down to a specific key +diff --git a/src/Features/SupportValidation/UnitTest.php b/src/Features/SupportValidation/UnitTest.php +index 4e7fd5bf..ab2199cf 100644 +--- a/src/Features/SupportValidation/UnitTest.php ++++ b/src/Features/SupportValidation/UnitTest.php +@@ -1303,6 +1303,26 @@ class UnitTest extends \Tests\TestCase + + $this->assertSame(1, ValidationUnwrappingSpyCollection::$toArrayCalls); + } ++ ++ public function test_validate_only_with_a_wildcard_field_only_validates_the_targeted_keys_in_each_item() ++ { ++ Livewire::test(new class extends TestComponent { ++ public $sections = [ ++ ['lines' => [['product' => 'Widget'], ['product' => '']]], ++ ['lines' => [['product' => ''], ['product' => '']]], ++ ]; ++ ++ public function validateFirstLines() ++ { ++ $this->validateOnly('sections.*.lines.0.product', [ ++ 'sections.*.lines.*.product' => 'required', ++ ]); ++ } ++ }) ++ ->call('validateFirstLines') ++ ->assertHasErrors('sections.1.lines.0.product') ++ ->assertHasNoErrors(['sections.0.lines.0.product', 'sections.0.lines.1.product', 'sections.1.lines.1.product']); ++ } + } + + class ValidationUnwrappingSpyCollection extends Collection diff --git a/tasks/livewire__livewire-10736/solution/solve.sh b/tasks/livewire__livewire-10736/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/livewire__livewire-10736/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/livewire__livewire-10736/task.toml b/tasks/livewire__livewire-10736/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..cdfca1ee41d88e31241c4844167ef805563e73bc --- /dev/null +++ b/tasks/livewire__livewire-10736/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/livewire__livewire-10736" +description = "[4.x] Fix wildcard `validateOnly()` validating untargeted sibling keys" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "livewire", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "livewire/livewire" +ref = "d0b4e22841d362dd213ee9602c399594d387b6ee" +reference = "https://github.com/livewire/livewire/pull/10736" +source_access = "auto" +built_at = "2026-11-16T16:09:51.425219+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:5ffbfbea62891438bdbb93f6222459e7ae3dd971109d61b9d254e721270c6a55" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-10-07T11:48:36Z" +diff_format = "unified" +context_files = [ + "src/Features/SupportValidation/HandlesValidation.php", + "src/Features/SupportValidation/UnitTest.php", +] +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.424150+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:108fd5bbaa619e83c7b309cc26c21beaddb12766fe0d939f64edd86f874f671a" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/livewire__livewire-10736/tests/capture.py b/tasks/livewire__livewire-10736/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/livewire__livewire-10736/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/livewire__livewire-10736/tests/instruction.md b/tasks/livewire__livewire-10736/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d63786c4f658791835689cfbf8c86262cc611c0f --- /dev/null +++ b/tasks/livewire__livewire-10736/tests/instruction.md @@ -0,0 +1,28 @@ +# Issue + +**Title:** [4.x] Fix wildcard `validateOnly()` validating untargeted sibling keys + +## Description + +When `validateOnly()` is given a field with a wildcard followed by a specific key, sibling keys in every item after the first get validated too: + +```php +public $sections = [ + ['lines' => [['product' => 'Widget'], ['product' => '']]], + ['lines' => [['product' => 'Gadget'], ['product' => '']]], +]; + +$this->validateOnly('sections.*.lines.0.product', [ + 'sections.*.lines.*.product' => 'required', +]); + +// Fails on sections.1.lines.1.product, which was never targeted. +``` + +`filterCollectionDataDownToSpecificKeys()` passes the same `$ruleKeys` / `$fieldKeys` collections into the recursive call for every item, and each call `shift()`s them. The first item consumes the remaining path, so later items are left unfiltered. + +This PR passes each item its own copy of the remaining keys, so every item is filtered the same way. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d0b4e22841d3`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10736/tests/oracle.patch b/tasks/livewire__livewire-10736/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..19e2afa5680e23970b697b8abeb5fc41a7dfc390 --- /dev/null +++ b/tasks/livewire__livewire-10736/tests/oracle.patch @@ -0,0 +1,44 @@ +diff --git a/src/Features/SupportValidation/HandlesValidation.php b/src/Features/SupportValidation/HandlesValidation.php +index 8bcd4d08..a0f1f6f5 100644 +--- a/src/Features/SupportValidation/HandlesValidation.php ++++ b/src/Features/SupportValidation/HandlesValidation.php +@@ -437,7 +437,7 @@ trait HandlesValidation + if ($fieldKey == '*') { + // If the specified field has a '*', then loop through the collection and keep the whole collection intact. + foreach ($data as $key => $value) { +- $data[$key] = $this->filterCollectionDataDownToSpecificKeys($value, $ruleKeys, $fieldKeys); ++ $data[$key] = $this->filterCollectionDataDownToSpecificKeys($value, clone $ruleKeys, clone $fieldKeys); + } + } else { + // Otherwise filter collection down to a specific key +diff --git a/src/Features/SupportValidation/UnitTest.php b/src/Features/SupportValidation/UnitTest.php +index 4e7fd5bf..ab2199cf 100644 +--- a/src/Features/SupportValidation/UnitTest.php ++++ b/src/Features/SupportValidation/UnitTest.php +@@ -1303,6 +1303,26 @@ class UnitTest extends \Tests\TestCase + + $this->assertSame(1, ValidationUnwrappingSpyCollection::$toArrayCalls); + } ++ ++ public function test_validate_only_with_a_wildcard_field_only_validates_the_targeted_keys_in_each_item() ++ { ++ Livewire::test(new class extends TestComponent { ++ public $sections = [ ++ ['lines' => [['product' => 'Widget'], ['product' => '']]], ++ ['lines' => [['product' => ''], ['product' => '']]], ++ ]; ++ ++ public function validateFirstLines() ++ { ++ $this->validateOnly('sections.*.lines.0.product', [ ++ 'sections.*.lines.*.product' => 'required', ++ ]); ++ } ++ }) ++ ->call('validateFirstLines') ++ ->assertHasErrors('sections.1.lines.0.product') ++ ->assertHasNoErrors(['sections.0.lines.0.product', 'sections.0.lines.1.product', 'sections.1.lines.1.product']); ++ } + } + + class ValidationUnwrappingSpyCollection extends Collection diff --git a/tasks/livewire__livewire-10736/tests/test.sh b/tasks/livewire__livewire-10736/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..f4255995d98bc2c91067af5b4e4a6a330f30ec75 --- /dev/null +++ b/tasks/livewire__livewire-10736/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace d0b4e22841d362dd213ee9602c399594d387b6ee > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/livewire__livewire-10736/tests/verifier.py b/tasks/livewire__livewire-10736/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/livewire__livewire-10736/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/livewire__livewire-10741/environment/Dockerfile b/tasks/livewire__livewire-10741/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2b0e159ee8ce195ce98a086105e83d9d0bd84fd4 --- /dev/null +++ b/tasks/livewire__livewire-10741/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/livewire/livewire.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/livewire/livewire.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/livewire/livewire.git +WORKDIR /workspace +RUN git fetch --depth 1 origin d0b4e22841d362dd213ee9602c399594d387b6ee 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard d0b4e22841d362dd213ee9602c399594d387b6ee \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base d0b4e22841d362dd213ee9602c399594d387b6ee \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/livewire__livewire-10741/instruction.md b/tasks/livewire__livewire-10741/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..354e2a1b4c35375a11d070b55c3cb2a8c2011280 --- /dev/null +++ b/tasks/livewire__livewire-10741/instruction.md @@ -0,0 +1,19 @@ +# Issue + +**Title:** [4.x] Fix resetting nested form object properties from the component + +## Description + +Resetting a nested form object property from the component only passes the last segment of the path to the form: + +```php +$this->reset('form.content.foo'); + +// Calls $this->form->reset('foo') instead of $this->form->reset('content.foo') +``` + +So the nested value is never restored. This PR passes everything after the form's property name (`content.foo`) to `Form::reset()`, which already supports dotted paths. Single level paths like `form.title` work the same as before. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d0b4e22841d3`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10741/solution/patch.diff b/tasks/livewire__livewire-10741/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..21318e932d33e89c0e8bcbef004c7d35993b3f4e --- /dev/null +++ b/tasks/livewire__livewire-10741/solution/patch.diff @@ -0,0 +1,41 @@ +diff --git a/src/Concerns/InteractsWithProperties.php b/src/Concerns/InteractsWithProperties.php +index 8816a71b..6843eb1f 100644 +--- a/src/Concerns/InteractsWithProperties.php ++++ b/src/Concerns/InteractsWithProperties.php +@@ -68,7 +68,7 @@ trait InteractsWithProperties + + // form object reset + if (is_subclass_of($this->{$objectName}, Form::class)) { +- $this->{$objectName}->reset($propertyName); ++ $this->{$objectName}->reset(Utils::afterFirstDot((string) $property)); + continue; + } + +diff --git a/src/Features/SupportFormObjects/UnitTest.php b/src/Features/SupportFormObjects/UnitTest.php +index dc9081f5..f1568639 100644 +--- a/src/Features/SupportFormObjects/UnitTest.php ++++ b/src/Features/SupportFormObjects/UnitTest.php +@@ -1234,6 +1234,23 @@ class UnitTest extends \Tests\TestCase + ->assertSetStrict('form.profile.name', '') + ->assertOk(); + } ++ ++ public function test_can_reset_a_nested_form_property_from_the_component() ++ { ++ Livewire::test(new class extends TestComponent { ++ public PostFormStubWithArrayDefaults $form; ++ ++ public function resetNestedFoo() ++ { ++ $this->reset('form.content.foo'); ++ } ++ }) ++ ->set('form.content.foo', ['bar' => 'changed']) ++ ->set('form.content.1', false) ++ ->call('resetNestedFoo') ++ ->assertSetStrict('form.content.foo', ['bar' => 'baz']) ++ ->assertSetStrict('form.content.1', false); ++ } + } + + class PostFormStub extends Form diff --git a/tasks/livewire__livewire-10741/solution/solve.sh b/tasks/livewire__livewire-10741/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/livewire__livewire-10741/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/livewire__livewire-10741/task.toml b/tasks/livewire__livewire-10741/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..b0dfd9672fd373e730af4a82776c6881bafb49c4 --- /dev/null +++ b/tasks/livewire__livewire-10741/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/livewire__livewire-10741" +description = "[4.x] Fix resetting nested form object properties from the component" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "livewire", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "livewire/livewire" +ref = "d0b4e22841d362dd213ee9602c399594d387b6ee" +reference = "https://github.com/livewire/livewire/pull/10741" +source_access = "auto" +built_at = "2026-11-16T16:09:51.426586+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:e69640729ac10ee6c4025ff6b308cf16780b41dca5a3ae3ecc139f539933223a" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-10-07T11:47:35Z" +diff_format = "unified" +context_files = [ + "src/Concerns/InteractsWithProperties.php", + "src/Features/SupportFormObjects/UnitTest.php", +] +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.424684+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:108fd5bbaa619e83c7b309cc26c21beaddb12766fe0d939f64edd86f874f671a" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/livewire__livewire-10741/tests/capture.py b/tasks/livewire__livewire-10741/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/livewire__livewire-10741/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/livewire__livewire-10741/tests/instruction.md b/tasks/livewire__livewire-10741/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..354e2a1b4c35375a11d070b55c3cb2a8c2011280 --- /dev/null +++ b/tasks/livewire__livewire-10741/tests/instruction.md @@ -0,0 +1,19 @@ +# Issue + +**Title:** [4.x] Fix resetting nested form object properties from the component + +## Description + +Resetting a nested form object property from the component only passes the last segment of the path to the form: + +```php +$this->reset('form.content.foo'); + +// Calls $this->form->reset('foo') instead of $this->form->reset('content.foo') +``` + +So the nested value is never restored. This PR passes everything after the form's property name (`content.foo`) to `Form::reset()`, which already supports dotted paths. Single level paths like `form.title` work the same as before. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d0b4e22841d3`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10741/tests/oracle.patch b/tasks/livewire__livewire-10741/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..21318e932d33e89c0e8bcbef004c7d35993b3f4e --- /dev/null +++ b/tasks/livewire__livewire-10741/tests/oracle.patch @@ -0,0 +1,41 @@ +diff --git a/src/Concerns/InteractsWithProperties.php b/src/Concerns/InteractsWithProperties.php +index 8816a71b..6843eb1f 100644 +--- a/src/Concerns/InteractsWithProperties.php ++++ b/src/Concerns/InteractsWithProperties.php +@@ -68,7 +68,7 @@ trait InteractsWithProperties + + // form object reset + if (is_subclass_of($this->{$objectName}, Form::class)) { +- $this->{$objectName}->reset($propertyName); ++ $this->{$objectName}->reset(Utils::afterFirstDot((string) $property)); + continue; + } + +diff --git a/src/Features/SupportFormObjects/UnitTest.php b/src/Features/SupportFormObjects/UnitTest.php +index dc9081f5..f1568639 100644 +--- a/src/Features/SupportFormObjects/UnitTest.php ++++ b/src/Features/SupportFormObjects/UnitTest.php +@@ -1234,6 +1234,23 @@ class UnitTest extends \Tests\TestCase + ->assertSetStrict('form.profile.name', '') + ->assertOk(); + } ++ ++ public function test_can_reset_a_nested_form_property_from_the_component() ++ { ++ Livewire::test(new class extends TestComponent { ++ public PostFormStubWithArrayDefaults $form; ++ ++ public function resetNestedFoo() ++ { ++ $this->reset('form.content.foo'); ++ } ++ }) ++ ->set('form.content.foo', ['bar' => 'changed']) ++ ->set('form.content.1', false) ++ ->call('resetNestedFoo') ++ ->assertSetStrict('form.content.foo', ['bar' => 'baz']) ++ ->assertSetStrict('form.content.1', false); ++ } + } + + class PostFormStub extends Form diff --git a/tasks/livewire__livewire-10741/tests/test.sh b/tasks/livewire__livewire-10741/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..f4255995d98bc2c91067af5b4e4a6a330f30ec75 --- /dev/null +++ b/tasks/livewire__livewire-10741/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace d0b4e22841d362dd213ee9602c399594d387b6ee > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/livewire__livewire-10741/tests/verifier.py b/tasks/livewire__livewire-10741/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/livewire__livewire-10741/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/livewire__livewire-10742/environment/Dockerfile b/tasks/livewire__livewire-10742/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2b0e159ee8ce195ce98a086105e83d9d0bd84fd4 --- /dev/null +++ b/tasks/livewire__livewire-10742/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/livewire/livewire.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/livewire/livewire.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/livewire/livewire.git +WORKDIR /workspace +RUN git fetch --depth 1 origin d0b4e22841d362dd213ee9602c399594d387b6ee 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard d0b4e22841d362dd213ee9602c399594d387b6ee \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base d0b4e22841d362dd213ee9602c399594d387b6ee \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/livewire__livewire-10742/instruction.md b/tasks/livewire__livewire-10742/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a84cf7a24f2795bc825f1e2d5270977e81d3662c --- /dev/null +++ b/tasks/livewire__livewire-10742/instruction.md @@ -0,0 +1,21 @@ +# Issue + +**Title:** [4.x] Fix queued `$set` dropping updates to properties that share its prefix + +## Description + +When a live `$set()` is queued, `mergeQueuedUpdates()` removes any pending update whose key *starts with* the queued key, so the queued value wins over stale nested updates. But `startsWith` also matches unrelated properties that just share a prefix: + +```blade + + + +``` + +Typing into `foobar` and then clicking the button sends `foo` but silently drops the pending `foobar` update. + +This PR only removes keys that are exactly the queued key or nested under it (`foo` or `foo.*`), so `foobar` is sent along with `foo`. It also resets `queuedUpdates` to `{}` instead of `[]` to match how it's initialized. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d0b4e22841d3`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10742/solution/patch.diff b/tasks/livewire__livewire-10742/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..960085b84f1659f899b58ba70c55593939efa0ac --- /dev/null +++ b/tasks/livewire__livewire-10742/solution/patch.diff @@ -0,0 +1,56 @@ +diff --git a/js/component.js b/js/component.js +index 804733a7..7917fa72 100644 +--- a/js/component.js ++++ b/js/component.js +@@ -109,7 +109,7 @@ export class Component { + // priority against ephemeral updates that have happend since them... + Object.entries(this.queuedUpdates).forEach(([updateKey, updateValue]) => { + Object.entries(diff).forEach(([diffKey, diffValue]) => { +- if (diffKey.startsWith(updateKey)) { ++ if (diffKey === updateKey || diffKey.startsWith(updateKey + '.')) { + delete diff[diffKey] + } + }) +@@ -117,7 +117,7 @@ export class Component { + diff[updateKey] = updateValue + }) + +- this.queuedUpdates = [] ++ this.queuedUpdates = {} + + return diff + } +diff --git a/src/Features/SupportDataBinding/BrowserTest.php b/src/Features/SupportDataBinding/BrowserTest.php +index bce71ff9..a21bdf2c 100644 +--- a/src/Features/SupportDataBinding/BrowserTest.php ++++ b/src/Features/SupportDataBinding/BrowserTest.php +@@ -1197,4 +1197,29 @@ class BrowserTest extends BrowserTestCase + ->assertSeeIn('@output', '{"0":"a","1":"b","1000":true}') + ; + } ++ ++ function test_queued_set_does_not_drop_updates_to_properties_that_share_its_prefix() ++ { ++ Livewire::visit(new class extends Component { ++ public $foo = ''; ++ ++ public $foobar = ''; ++ ++ public function render() ++ { ++ return <<<'BLADE' ++
++ ++ ++ ++ ++ {{ $foo }}-{{ $foobar }} ++
++ BLADE; ++ } ++ }) ++ ->type('@foobar', 'baz') ++ ->waitForLivewire()->click('@set') ++ ->assertSeeIn('@output', 'bar-baz'); ++ } + } diff --git a/tasks/livewire__livewire-10742/solution/solve.sh b/tasks/livewire__livewire-10742/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/livewire__livewire-10742/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/livewire__livewire-10742/task.toml b/tasks/livewire__livewire-10742/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..01f4e31f194c1ec18a6b44ee10c8055a3f6da07c --- /dev/null +++ b/tasks/livewire__livewire-10742/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/livewire__livewire-10742" +description = "[4.x] Fix queued `$set` dropping updates to properties that share its prefix" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "livewire", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "livewire/livewire" +ref = "d0b4e22841d362dd213ee9602c399594d387b6ee" +reference = "https://github.com/livewire/livewire/pull/10742" +source_access = "auto" +built_at = "2026-11-16T16:09:51.430477+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:08fbc805d0b3fc5a04df4f817bd18e8aa32406bf3e204b582aad5b2f6db4b519" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-10-07T11:46:52Z" +diff_format = "unified" +context_files = [ + "js/component.js", + "src/Features/SupportDataBinding/BrowserTest.php", +] +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.425234+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:108fd5bbaa619e83c7b309cc26c21beaddb12766fe0d939f64edd86f874f671a" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/livewire__livewire-10742/tests/capture.py b/tasks/livewire__livewire-10742/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/livewire__livewire-10742/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/livewire__livewire-10742/tests/instruction.md b/tasks/livewire__livewire-10742/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a84cf7a24f2795bc825f1e2d5270977e81d3662c --- /dev/null +++ b/tasks/livewire__livewire-10742/tests/instruction.md @@ -0,0 +1,21 @@ +# Issue + +**Title:** [4.x] Fix queued `$set` dropping updates to properties that share its prefix + +## Description + +When a live `$set()` is queued, `mergeQueuedUpdates()` removes any pending update whose key *starts with* the queued key, so the queued value wins over stale nested updates. But `startsWith` also matches unrelated properties that just share a prefix: + +```blade + + + +``` + +Typing into `foobar` and then clicking the button sends `foo` but silently drops the pending `foobar` update. + +This PR only removes keys that are exactly the queued key or nested under it (`foo` or `foo.*`), so `foobar` is sent along with `foo`. It also resets `queuedUpdates` to `{}` instead of `[]` to match how it's initialized. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d0b4e22841d3`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10742/tests/oracle.patch b/tasks/livewire__livewire-10742/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..960085b84f1659f899b58ba70c55593939efa0ac --- /dev/null +++ b/tasks/livewire__livewire-10742/tests/oracle.patch @@ -0,0 +1,56 @@ +diff --git a/js/component.js b/js/component.js +index 804733a7..7917fa72 100644 +--- a/js/component.js ++++ b/js/component.js +@@ -109,7 +109,7 @@ export class Component { + // priority against ephemeral updates that have happend since them... + Object.entries(this.queuedUpdates).forEach(([updateKey, updateValue]) => { + Object.entries(diff).forEach(([diffKey, diffValue]) => { +- if (diffKey.startsWith(updateKey)) { ++ if (diffKey === updateKey || diffKey.startsWith(updateKey + '.')) { + delete diff[diffKey] + } + }) +@@ -117,7 +117,7 @@ export class Component { + diff[updateKey] = updateValue + }) + +- this.queuedUpdates = [] ++ this.queuedUpdates = {} + + return diff + } +diff --git a/src/Features/SupportDataBinding/BrowserTest.php b/src/Features/SupportDataBinding/BrowserTest.php +index bce71ff9..a21bdf2c 100644 +--- a/src/Features/SupportDataBinding/BrowserTest.php ++++ b/src/Features/SupportDataBinding/BrowserTest.php +@@ -1197,4 +1197,29 @@ class BrowserTest extends BrowserTestCase + ->assertSeeIn('@output', '{"0":"a","1":"b","1000":true}') + ; + } ++ ++ function test_queued_set_does_not_drop_updates_to_properties_that_share_its_prefix() ++ { ++ Livewire::visit(new class extends Component { ++ public $foo = ''; ++ ++ public $foobar = ''; ++ ++ public function render() ++ { ++ return <<<'BLADE' ++
++ ++ ++ ++ ++ {{ $foo }}-{{ $foobar }} ++
++ BLADE; ++ } ++ }) ++ ->type('@foobar', 'baz') ++ ->waitForLivewire()->click('@set') ++ ->assertSeeIn('@output', 'bar-baz'); ++ } + } diff --git a/tasks/livewire__livewire-10742/tests/test.sh b/tasks/livewire__livewire-10742/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..f4255995d98bc2c91067af5b4e4a6a330f30ec75 --- /dev/null +++ b/tasks/livewire__livewire-10742/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace d0b4e22841d362dd213ee9602c399594d387b6ee > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/livewire__livewire-10742/tests/verifier.py b/tasks/livewire__livewire-10742/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/livewire__livewire-10742/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/livewire__livewire-10743/environment/Dockerfile b/tasks/livewire__livewire-10743/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2b0e159ee8ce195ce98a086105e83d9d0bd84fd4 --- /dev/null +++ b/tasks/livewire__livewire-10743/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/livewire/livewire.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/livewire/livewire.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/livewire/livewire.git +WORKDIR /workspace +RUN git fetch --depth 1 origin d0b4e22841d362dd213ee9602c399594d387b6ee 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard d0b4e22841d362dd213ee9602c399594d387b6ee \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base d0b4e22841d362dd213ee9602c399594d387b6ee \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/livewire__livewire-10743/instruction.md b/tasks/livewire__livewire-10743/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..92a1c34cc56cadd7becaa5d95b19839b455f60ec --- /dev/null +++ b/tasks/livewire__livewire-10743/instruction.md @@ -0,0 +1,21 @@ +# Issue + +**Title:** [4.x] Throw when redirecting to a component whose route needs parameters + +## Description + +Redirecting to a component whose `Route::livewire()` route has parameters sends the browser to the raw route pattern: + +```php +Route::livewire('/posts/{post}', ShowPost::class); + +$this->redirect(ShowPost::class); // redirects to /posts/%7Bpost%7D +``` + +`resolveComponentUrl()` was building the URL with `url($route->uri())`, which never fills in parameters. This PR generates it with `url()->toRoute()` instead, so a missing required parameter throws Laravel's usual `UrlGenerationException` (same as `route()` or `url()->action()` would) and optional parameters are dropped rather than left in the URL. Parameterless routes behave exactly as before. + +If you need parameters, use `redirectRoute('posts.show', ['post' => $post])`. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d0b4e22841d3`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10743/solution/patch.diff b/tasks/livewire__livewire-10743/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..37128f230071008d47e7dc73118f30a6d2e60db1 --- /dev/null +++ b/tasks/livewire__livewire-10743/solution/patch.diff @@ -0,0 +1,46 @@ +diff --git a/src/Features/SupportRedirects/SupportRedirects.php b/src/Features/SupportRedirects/SupportRedirects.php +index 516858dd..fdc754f4 100644 +--- a/src/Features/SupportRedirects/SupportRedirects.php ++++ b/src/Features/SupportRedirects/SupportRedirects.php +@@ -99,7 +99,7 @@ class SupportRedirects extends ComponentHook + : app('livewire.factory')->resolveComponentClass($routeComponent); + + if ($resolvedClass === $componentClass) { +- return url($route->uri()); ++ return url()->toRoute($route, [], true); + } + } + } +diff --git a/src/Features/SupportRedirects/UnitTest.php b/src/Features/SupportRedirects/UnitTest.php +index 9c64f7d4..92fd3337 100644 +--- a/src/Features/SupportRedirects/UnitTest.php ++++ b/src/Features/SupportRedirects/UnitTest.php +@@ -3,6 +3,7 @@ + namespace Livewire\Features\SupportRedirects; + + use Illuminate\Http\RedirectResponse; ++use Illuminate\Routing\Exceptions\UrlGenerationException; + use Illuminate\Support\Facades\Redirect; + use Illuminate\Support\Facades\Route; + use Illuminate\Support\Facades\Session; +@@ -297,6 +298,20 @@ class UnitTest extends \Tests\TestCase + $this->assertNull($component->effects['returns'][0]); + } + ++ public function test_redirect_to_component_with_parameterized_livewire_route_throws_missing_parameter_exception() ++ { ++ Route::livewire('/posts/{post}', TriggersRedirectStub::class); ++ ++ $this->expectException(UrlGenerationException::class); ++ ++ Livewire::test(new class extends TestComponent { ++ function triggerRedirect() ++ { ++ $this->redirect(TriggersRedirectStub::class); ++ } ++ })->call('triggerRedirect'); ++ } ++ + protected function registerNamedRoute() + { + Route::get('foo', function () { diff --git a/tasks/livewire__livewire-10743/solution/solve.sh b/tasks/livewire__livewire-10743/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/livewire__livewire-10743/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/livewire__livewire-10743/task.toml b/tasks/livewire__livewire-10743/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..037d9b03871a83947c758eeae1233ab892b70163 --- /dev/null +++ b/tasks/livewire__livewire-10743/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/livewire__livewire-10743" +description = "[4.x] Throw when redirecting to a component whose route needs parameters" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "livewire", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "livewire/livewire" +ref = "d0b4e22841d362dd213ee9602c399594d387b6ee" +reference = "https://github.com/livewire/livewire/pull/10743" +source_access = "auto" +built_at = "2026-11-16T16:09:51.428213+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:f93a048207a8e3278b237802ba06408eb598860c457d0fd197f7daadf0fb3140" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-10-07T11:46:27Z" +diff_format = "unified" +context_files = [ + "src/Features/SupportRedirects/SupportRedirects.php", + "src/Features/SupportRedirects/UnitTest.php", +] +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.425764+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:108fd5bbaa619e83c7b309cc26c21beaddb12766fe0d939f64edd86f874f671a" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/livewire__livewire-10743/tests/capture.py b/tasks/livewire__livewire-10743/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/livewire__livewire-10743/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/livewire__livewire-10743/tests/instruction.md b/tasks/livewire__livewire-10743/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..92a1c34cc56cadd7becaa5d95b19839b455f60ec --- /dev/null +++ b/tasks/livewire__livewire-10743/tests/instruction.md @@ -0,0 +1,21 @@ +# Issue + +**Title:** [4.x] Throw when redirecting to a component whose route needs parameters + +## Description + +Redirecting to a component whose `Route::livewire()` route has parameters sends the browser to the raw route pattern: + +```php +Route::livewire('/posts/{post}', ShowPost::class); + +$this->redirect(ShowPost::class); // redirects to /posts/%7Bpost%7D +``` + +`resolveComponentUrl()` was building the URL with `url($route->uri())`, which never fills in parameters. This PR generates it with `url()->toRoute()` instead, so a missing required parameter throws Laravel's usual `UrlGenerationException` (same as `route()` or `url()->action()` would) and optional parameters are dropped rather than left in the URL. Parameterless routes behave exactly as before. + +If you need parameters, use `redirectRoute('posts.show', ['post' => $post])`. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d0b4e22841d3`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10743/tests/oracle.patch b/tasks/livewire__livewire-10743/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..37128f230071008d47e7dc73118f30a6d2e60db1 --- /dev/null +++ b/tasks/livewire__livewire-10743/tests/oracle.patch @@ -0,0 +1,46 @@ +diff --git a/src/Features/SupportRedirects/SupportRedirects.php b/src/Features/SupportRedirects/SupportRedirects.php +index 516858dd..fdc754f4 100644 +--- a/src/Features/SupportRedirects/SupportRedirects.php ++++ b/src/Features/SupportRedirects/SupportRedirects.php +@@ -99,7 +99,7 @@ class SupportRedirects extends ComponentHook + : app('livewire.factory')->resolveComponentClass($routeComponent); + + if ($resolvedClass === $componentClass) { +- return url($route->uri()); ++ return url()->toRoute($route, [], true); + } + } + } +diff --git a/src/Features/SupportRedirects/UnitTest.php b/src/Features/SupportRedirects/UnitTest.php +index 9c64f7d4..92fd3337 100644 +--- a/src/Features/SupportRedirects/UnitTest.php ++++ b/src/Features/SupportRedirects/UnitTest.php +@@ -3,6 +3,7 @@ + namespace Livewire\Features\SupportRedirects; + + use Illuminate\Http\RedirectResponse; ++use Illuminate\Routing\Exceptions\UrlGenerationException; + use Illuminate\Support\Facades\Redirect; + use Illuminate\Support\Facades\Route; + use Illuminate\Support\Facades\Session; +@@ -297,6 +298,20 @@ class UnitTest extends \Tests\TestCase + $this->assertNull($component->effects['returns'][0]); + } + ++ public function test_redirect_to_component_with_parameterized_livewire_route_throws_missing_parameter_exception() ++ { ++ Route::livewire('/posts/{post}', TriggersRedirectStub::class); ++ ++ $this->expectException(UrlGenerationException::class); ++ ++ Livewire::test(new class extends TestComponent { ++ function triggerRedirect() ++ { ++ $this->redirect(TriggersRedirectStub::class); ++ } ++ })->call('triggerRedirect'); ++ } ++ + protected function registerNamedRoute() + { + Route::get('foo', function () { diff --git a/tasks/livewire__livewire-10743/tests/test.sh b/tasks/livewire__livewire-10743/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..f4255995d98bc2c91067af5b4e4a6a330f30ec75 --- /dev/null +++ b/tasks/livewire__livewire-10743/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace d0b4e22841d362dd213ee9602c399594d387b6ee > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/livewire__livewire-10743/tests/verifier.py b/tasks/livewire__livewire-10743/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/livewire__livewire-10743/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/livewire__livewire-10744/environment/Dockerfile b/tasks/livewire__livewire-10744/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2b0e159ee8ce195ce98a086105e83d9d0bd84fd4 --- /dev/null +++ b/tasks/livewire__livewire-10744/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/livewire/livewire.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/livewire/livewire.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/livewire/livewire.git +WORKDIR /workspace +RUN git fetch --depth 1 origin d0b4e22841d362dd213ee9602c399594d387b6ee 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard d0b4e22841d362dd213ee9602c399594d387b6ee \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base d0b4e22841d362dd213ee9602c399594d387b6ee \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/livewire__livewire-10744/instruction.md b/tasks/livewire__livewire-10744/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6ad52abcd3a7462037519d62d4937852b20abc07 --- /dev/null +++ b/tasks/livewire__livewire-10744/instruction.md @@ -0,0 +1,18 @@ +# Issue + +**Title:** [4.x] Return 404 instead of 500 when component JS or CSS asset does not exist + +## Description + +Requesting a component JS or CSS module that doesn't exist currently throws and returns a 500: + +``` +GET /livewire-xxxx/js/does-not-exist.js -> ComponentNotFoundException +GET /livewire-xxxx/css/some-component.css -> Exception: Component ... does not have a style source +``` + +These URLs are public, so scanners and stale caches hitting them fill error trackers with noise. This PR returns a 404 instead when the component doesn't exist, has no module, or the module file is missing. It applies to the `js/{component}.js`, `css/{component}.css`, and `css/{component}.global.css` routes. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d0b4e22841d3`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10744/solution/patch.diff b/tasks/livewire__livewire-10744/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..9962c526f771af86c3993676f297c8032827f210 --- /dev/null +++ b/tasks/livewire__livewire-10744/solution/patch.diff @@ -0,0 +1,167 @@ +diff --git a/src/Features/SupportCssModules/SupportCssModules.php b/src/Features/SupportCssModules/SupportCssModules.php +index 2bc3e338..6f812742 100644 +--- a/src/Features/SupportCssModules/SupportCssModules.php ++++ b/src/Features/SupportCssModules/SupportCssModules.php +@@ -5,6 +5,7 @@ namespace Livewire\Features\SupportCssModules; + use Illuminate\Support\Facades\Route; + use Livewire\ComponentHook; + use Livewire\Drawer\Utils; ++use Livewire\Exceptions\ComponentNotFoundException; + use Livewire\Mechanisms\HandleRequests\EndpointResolver; + + class SupportCssModules extends ComponentHook +@@ -17,17 +18,17 @@ class SupportCssModules extends ComponentHook + $component = str_replace('---', '::', $component); + $component = str_replace('--', '.', $component); + +- $instance = app('livewire')->new($component); +- +- if (! method_exists($instance, 'styleModuleSrc')) { +- throw new \Exception('Component '.$component.' does not have a style source.'); ++ try { ++ $instance = app('livewire')->new($component); ++ } catch (ComponentNotFoundException) { ++ abort(404); + } + ++ abort_unless(method_exists($instance, 'styleModuleSrc'), 404); ++ + $path = $instance->styleModuleSrc(); + +- if (! file_exists($path)) { +- throw new \Exception('Style file not found: '.$path); +- } ++ abort_unless(file_exists($path), 404); + + $css = file_get_contents($path); + +@@ -50,17 +51,17 @@ class SupportCssModules extends ComponentHook + $component = str_replace('---', '::', $component); + $component = str_replace('--', '.', $component); + +- $instance = app('livewire')->new($component); +- +- if (! method_exists($instance, 'globalStyleModuleSrc')) { +- throw new \Exception('Component '.$component.' does not have a global style source.'); ++ try { ++ $instance = app('livewire')->new($component); ++ } catch (ComponentNotFoundException) { ++ abort(404); + } + ++ abort_unless(method_exists($instance, 'globalStyleModuleSrc'), 404); ++ + $path = $instance->globalStyleModuleSrc(); + +- if (! file_exists($path)) { +- throw new \Exception('Global style file not found: '.$path); +- } ++ abort_unless(file_exists($path), 404); + + $css = file_get_contents($path); + +diff --git a/src/Features/SupportCssModules/UnitTest.php b/src/Features/SupportCssModules/UnitTest.php +new file mode 100644 +index 00000000..b2269ccc +--- /dev/null ++++ b/src/Features/SupportCssModules/UnitTest.php +@@ -0,0 +1,21 @@ ++addNamespace('testns', viewPath: __DIR__.'/fixtures'); ++ ++ $prefix = EndpointResolver::prefix(); ++ ++ $this->get("{$prefix}/css/non-existent.css")->assertNotFound(); ++ $this->get("{$prefix}/css/non-existent.global.css")->assertNotFound(); ++ $this->get("{$prefix}/css/testns---no-module.css")->assertNotFound(); ++ $this->get("{$prefix}/css/testns---no-module.global.css")->assertNotFound(); ++ } ++} +diff --git a/src/Features/SupportCssModules/fixtures/no-module.blade.php b/src/Features/SupportCssModules/fixtures/no-module.blade.php +new file mode 100644 +index 00000000..2bb1fe26 +--- /dev/null ++++ b/src/Features/SupportCssModules/fixtures/no-module.blade.php +@@ -0,0 +1,10 @@ ++ ++ ++
++ no style here ++
+diff --git a/src/Features/SupportJsModules/SupportJsModules.php b/src/Features/SupportJsModules/SupportJsModules.php +index dbdab181..0d8ca617 100644 +--- a/src/Features/SupportJsModules/SupportJsModules.php ++++ b/src/Features/SupportJsModules/SupportJsModules.php +@@ -5,6 +5,7 @@ namespace Livewire\Features\SupportJsModules; + use Illuminate\Support\Facades\Route; + use Livewire\ComponentHook; + use Livewire\Drawer\Utils; ++use Livewire\Exceptions\ComponentNotFoundException; + use Livewire\Features\SupportScriptsAndAssets\SupportScriptsAndAssets; + use Livewire\Mechanisms\HandleRequests\EndpointResolver; + +@@ -25,17 +26,17 @@ class SupportJsModules extends ComponentHook + $component = str_replace('---', '::', $component); + $component = str_replace('--', '.', $component); + +- $instance = app('livewire')->new($component); +- +- if (! method_exists($instance, 'scriptModuleSrc')) { +- throw new \Exception('Component '.$component.' does not have a script source.'); ++ try { ++ $instance = app('livewire')->new($component); ++ } catch (ComponentNotFoundException) { ++ abort(404); + } + ++ abort_unless(method_exists($instance, 'scriptModuleSrc'), 404); ++ + $path = $instance->scriptModuleSrc(); + +- if (! file_exists($path)) { +- throw new \Exception('Script file not found: '.$path); +- } ++ abort_unless(file_exists($path), 404); + + $source = file_get_contents($path); + +diff --git a/src/Features/SupportJsModules/UnitTest.php b/src/Features/SupportJsModules/UnitTest.php +index 468fd92e..eafb1a53 100644 +--- a/src/Features/SupportJsModules/UnitTest.php ++++ b/src/Features/SupportJsModules/UnitTest.php +@@ -5,6 +5,7 @@ namespace Livewire\Features\SupportJsModules; + use Illuminate\Support\Facades\Route; + use Livewire\Component; + use Livewire\Livewire; ++use Livewire\Mechanisms\HandleRequests\EndpointResolver; + + class UnitTest extends \Tests\TestCase + { +@@ -133,4 +134,12 @@ class UnitTest extends \Tests\TestCase + + $this->assertArrayNotHasKey('childScriptModules', $component->effects); + } ++ ++ public function test_missing_js_modules_return_404() ++ { ++ $prefix = EndpointResolver::prefix(); ++ ++ $this->get("{$prefix}/js/non-existent.js")->assertNotFound(); ++ $this->get("{$prefix}/js/testns---no-module.js")->assertNotFound(); ++ } + } diff --git a/tasks/livewire__livewire-10744/solution/solve.sh b/tasks/livewire__livewire-10744/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/livewire__livewire-10744/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/livewire__livewire-10744/task.toml b/tasks/livewire__livewire-10744/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f1f6f2c909ee32b16f46123990a5a7b7de31fd5f --- /dev/null +++ b/tasks/livewire__livewire-10744/task.toml @@ -0,0 +1,72 @@ +version = "1.0" + +[task] +name = "trending/livewire__livewire-10744" +description = "[4.x] Return 404 instead of 500 when component JS or CSS asset does not exist" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "livewire", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "livewire/livewire" +ref = "d0b4e22841d362dd213ee9602c399594d387b6ee" +reference = "https://github.com/livewire/livewire/pull/10744" +source_access = "auto" +built_at = "2026-11-16T16:09:51.432373+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:3ead9ece2d6c6246b31d06bbfc30ab9afcc3d1964066902a1e41aa7ac2ba3a0b" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-10-07T11:44:53Z" +diff_format = "unified" +context_files = [ + "src/Features/SupportCssModules/SupportCssModules.php", + "src/Features/SupportCssModules/UnitTest.php", + "src/Features/SupportCssModules/fixtures/no-module.blade.php", + "src/Features/SupportJsModules/SupportJsModules.php", + "src/Features/SupportJsModules/UnitTest.php", +] +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.426322+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:108fd5bbaa619e83c7b309cc26c21beaddb12766fe0d939f64edd86f874f671a" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/livewire__livewire-10744/tests/capture.py b/tasks/livewire__livewire-10744/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/livewire__livewire-10744/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/livewire__livewire-10744/tests/instruction.md b/tasks/livewire__livewire-10744/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6ad52abcd3a7462037519d62d4937852b20abc07 --- /dev/null +++ b/tasks/livewire__livewire-10744/tests/instruction.md @@ -0,0 +1,18 @@ +# Issue + +**Title:** [4.x] Return 404 instead of 500 when component JS or CSS asset does not exist + +## Description + +Requesting a component JS or CSS module that doesn't exist currently throws and returns a 500: + +``` +GET /livewire-xxxx/js/does-not-exist.js -> ComponentNotFoundException +GET /livewire-xxxx/css/some-component.css -> Exception: Component ... does not have a style source +``` + +These URLs are public, so scanners and stale caches hitting them fill error trackers with noise. This PR returns a 404 instead when the component doesn't exist, has no module, or the module file is missing. It applies to the `js/{component}.js`, `css/{component}.css`, and `css/{component}.global.css` routes. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d0b4e22841d3`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10744/tests/oracle.patch b/tasks/livewire__livewire-10744/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..9962c526f771af86c3993676f297c8032827f210 --- /dev/null +++ b/tasks/livewire__livewire-10744/tests/oracle.patch @@ -0,0 +1,167 @@ +diff --git a/src/Features/SupportCssModules/SupportCssModules.php b/src/Features/SupportCssModules/SupportCssModules.php +index 2bc3e338..6f812742 100644 +--- a/src/Features/SupportCssModules/SupportCssModules.php ++++ b/src/Features/SupportCssModules/SupportCssModules.php +@@ -5,6 +5,7 @@ namespace Livewire\Features\SupportCssModules; + use Illuminate\Support\Facades\Route; + use Livewire\ComponentHook; + use Livewire\Drawer\Utils; ++use Livewire\Exceptions\ComponentNotFoundException; + use Livewire\Mechanisms\HandleRequests\EndpointResolver; + + class SupportCssModules extends ComponentHook +@@ -17,17 +18,17 @@ class SupportCssModules extends ComponentHook + $component = str_replace('---', '::', $component); + $component = str_replace('--', '.', $component); + +- $instance = app('livewire')->new($component); +- +- if (! method_exists($instance, 'styleModuleSrc')) { +- throw new \Exception('Component '.$component.' does not have a style source.'); ++ try { ++ $instance = app('livewire')->new($component); ++ } catch (ComponentNotFoundException) { ++ abort(404); + } + ++ abort_unless(method_exists($instance, 'styleModuleSrc'), 404); ++ + $path = $instance->styleModuleSrc(); + +- if (! file_exists($path)) { +- throw new \Exception('Style file not found: '.$path); +- } ++ abort_unless(file_exists($path), 404); + + $css = file_get_contents($path); + +@@ -50,17 +51,17 @@ class SupportCssModules extends ComponentHook + $component = str_replace('---', '::', $component); + $component = str_replace('--', '.', $component); + +- $instance = app('livewire')->new($component); +- +- if (! method_exists($instance, 'globalStyleModuleSrc')) { +- throw new \Exception('Component '.$component.' does not have a global style source.'); ++ try { ++ $instance = app('livewire')->new($component); ++ } catch (ComponentNotFoundException) { ++ abort(404); + } + ++ abort_unless(method_exists($instance, 'globalStyleModuleSrc'), 404); ++ + $path = $instance->globalStyleModuleSrc(); + +- if (! file_exists($path)) { +- throw new \Exception('Global style file not found: '.$path); +- } ++ abort_unless(file_exists($path), 404); + + $css = file_get_contents($path); + +diff --git a/src/Features/SupportCssModules/UnitTest.php b/src/Features/SupportCssModules/UnitTest.php +new file mode 100644 +index 00000000..b2269ccc +--- /dev/null ++++ b/src/Features/SupportCssModules/UnitTest.php +@@ -0,0 +1,21 @@ ++addNamespace('testns', viewPath: __DIR__.'/fixtures'); ++ ++ $prefix = EndpointResolver::prefix(); ++ ++ $this->get("{$prefix}/css/non-existent.css")->assertNotFound(); ++ $this->get("{$prefix}/css/non-existent.global.css")->assertNotFound(); ++ $this->get("{$prefix}/css/testns---no-module.css")->assertNotFound(); ++ $this->get("{$prefix}/css/testns---no-module.global.css")->assertNotFound(); ++ } ++} +diff --git a/src/Features/SupportCssModules/fixtures/no-module.blade.php b/src/Features/SupportCssModules/fixtures/no-module.blade.php +new file mode 100644 +index 00000000..2bb1fe26 +--- /dev/null ++++ b/src/Features/SupportCssModules/fixtures/no-module.blade.php +@@ -0,0 +1,10 @@ ++ ++ ++
++ no style here ++
+diff --git a/src/Features/SupportJsModules/SupportJsModules.php b/src/Features/SupportJsModules/SupportJsModules.php +index dbdab181..0d8ca617 100644 +--- a/src/Features/SupportJsModules/SupportJsModules.php ++++ b/src/Features/SupportJsModules/SupportJsModules.php +@@ -5,6 +5,7 @@ namespace Livewire\Features\SupportJsModules; + use Illuminate\Support\Facades\Route; + use Livewire\ComponentHook; + use Livewire\Drawer\Utils; ++use Livewire\Exceptions\ComponentNotFoundException; + use Livewire\Features\SupportScriptsAndAssets\SupportScriptsAndAssets; + use Livewire\Mechanisms\HandleRequests\EndpointResolver; + +@@ -25,17 +26,17 @@ class SupportJsModules extends ComponentHook + $component = str_replace('---', '::', $component); + $component = str_replace('--', '.', $component); + +- $instance = app('livewire')->new($component); +- +- if (! method_exists($instance, 'scriptModuleSrc')) { +- throw new \Exception('Component '.$component.' does not have a script source.'); ++ try { ++ $instance = app('livewire')->new($component); ++ } catch (ComponentNotFoundException) { ++ abort(404); + } + ++ abort_unless(method_exists($instance, 'scriptModuleSrc'), 404); ++ + $path = $instance->scriptModuleSrc(); + +- if (! file_exists($path)) { +- throw new \Exception('Script file not found: '.$path); +- } ++ abort_unless(file_exists($path), 404); + + $source = file_get_contents($path); + +diff --git a/src/Features/SupportJsModules/UnitTest.php b/src/Features/SupportJsModules/UnitTest.php +index 468fd92e..eafb1a53 100644 +--- a/src/Features/SupportJsModules/UnitTest.php ++++ b/src/Features/SupportJsModules/UnitTest.php +@@ -5,6 +5,7 @@ namespace Livewire\Features\SupportJsModules; + use Illuminate\Support\Facades\Route; + use Livewire\Component; + use Livewire\Livewire; ++use Livewire\Mechanisms\HandleRequests\EndpointResolver; + + class UnitTest extends \Tests\TestCase + { +@@ -133,4 +134,12 @@ class UnitTest extends \Tests\TestCase + + $this->assertArrayNotHasKey('childScriptModules', $component->effects); + } ++ ++ public function test_missing_js_modules_return_404() ++ { ++ $prefix = EndpointResolver::prefix(); ++ ++ $this->get("{$prefix}/js/non-existent.js")->assertNotFound(); ++ $this->get("{$prefix}/js/testns---no-module.js")->assertNotFound(); ++ } + } diff --git a/tasks/livewire__livewire-10744/tests/test.sh b/tasks/livewire__livewire-10744/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..f4255995d98bc2c91067af5b4e4a6a330f30ec75 --- /dev/null +++ b/tasks/livewire__livewire-10744/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace d0b4e22841d362dd213ee9602c399594d387b6ee > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/livewire__livewire-10744/tests/verifier.py b/tasks/livewire__livewire-10744/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/livewire__livewire-10744/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/livewire__livewire-10747/environment/Dockerfile b/tasks/livewire__livewire-10747/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cc2c3f1abe1943655b870b626f58f447d3eb062f --- /dev/null +++ b/tasks/livewire__livewire-10747/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/livewire/livewire.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/livewire/livewire.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/livewire/livewire.git +WORKDIR /workspace +RUN git fetch --depth 1 origin f3b74902cf06647cd08a26847cd48ed9fbf6f424 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard f3b74902cf06647cd08a26847cd48ed9fbf6f424 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base f3b74902cf06647cd08a26847cd48ed9fbf6f424 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/livewire__livewire-10747/instruction.md b/tasks/livewire__livewire-10747/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..90b2d501b87dc86019155fc9473448e458112aab --- /dev/null +++ b/tasks/livewire__livewire-10747/instruction.md @@ -0,0 +1,22 @@ +# Issue + +**Title:** [4.x] Fix `Form::resetErrorBag()` clearing the entire component error bag + +## Description + +Calling `resetErrorBag()` (or `resetValidation()` / `clearValidation()`) on a form object with no arguments wipes the entire component's error bag, not just the form's errors: + +```php +$this->addError('other', '...'); +$this->form->addError('title', '...'); + +$this->form->resetErrorBag(); // Also clears "other"... +``` + +This happens because the form passes an empty array to the component's `resetErrorBag()`, which treats an empty list as "clear everything". This PR resets `form.*` instead, so only that form's errors are cleared. Passing specific fields works the same as before. + +Note that a successful `$this->form->validate()` also calls `resetErrorBag()`, so it now only clears the form's own errors rather than every error on the component. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `f3b74902cf06`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10747/solution/patch.diff b/tasks/livewire__livewire-10747/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..a99ee37efee001f230d3e5fec164e2912ba8fe99 --- /dev/null +++ b/tasks/livewire__livewire-10747/solution/patch.diff @@ -0,0 +1,49 @@ +diff --git a/src/Features/SupportFormObjects/Form.php b/src/Features/SupportFormObjects/Form.php +index d1387640..a03c25ab 100644 +--- a/src/Features/SupportFormObjects/Form.php ++++ b/src/Features/SupportFormObjects/Form.php +@@ -83,7 +83,7 @@ class Form implements Arrayable + + public function resetErrorBag($field = null) + { +- $fields = (array) $field; ++ $fields = (array) ($field ?: '*'); + + foreach ($fields as $idx => $field) { + $fields[$idx] = $this->propertyName . '.' . $field; +diff --git a/src/Features/SupportFormObjects/UnitTest.php b/src/Features/SupportFormObjects/UnitTest.php +index f1568639..69bcb718 100644 +--- a/src/Features/SupportFormObjects/UnitTest.php ++++ b/src/Features/SupportFormObjects/UnitTest.php +@@ -1235,6 +1235,31 @@ class UnitTest extends \Tests\TestCase + ->assertOk(); + } + ++ public function test_resetting_a_forms_error_bag_only_clears_that_forms_errors() ++ { ++ Livewire::test(new class extends TestComponent { ++ public $other = ''; ++ ++ public PostFormStub $form; ++ ++ public function addErrors() ++ { ++ $this->addError('other', 'component error'); ++ $this->form->addError('title', 'form error'); ++ } ++ ++ public function clearFormErrors() ++ { ++ $this->form->resetErrorBag(); ++ } ++ }) ++ ->call('addErrors') ++ ->assertHasErrors(['other', 'form.title']) ++ ->call('clearFormErrors') ++ ->assertHasErrors(['other']) ++ ->assertHasNoErrors(['form.title']); ++ } ++ + public function test_can_reset_a_nested_form_property_from_the_component() + { + Livewire::test(new class extends TestComponent { diff --git a/tasks/livewire__livewire-10747/solution/solve.sh b/tasks/livewire__livewire-10747/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/livewire__livewire-10747/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/livewire__livewire-10747/task.toml b/tasks/livewire__livewire-10747/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..62274f90c389e9b2ff41348c2f9d85982113a080 --- /dev/null +++ b/tasks/livewire__livewire-10747/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/livewire__livewire-10747" +description = "[4.x] Fix `Form::resetErrorBag()` clearing the entire component error bag" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "livewire", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "livewire/livewire" +ref = "f3b74902cf06647cd08a26847cd48ed9fbf6f424" +reference = "https://github.com/livewire/livewire/pull/10747" +source_access = "auto" +built_at = "2026-11-16T16:09:51.396952+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:5fa839e8fa143383de2c3527febbf8ccf54142f638a0d0418e5e888affe01037" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-10-07T12:43:58Z" +diff_format = "unified" +context_files = [ + "src/Features/SupportFormObjects/Form.php", + "src/Features/SupportFormObjects/UnitTest.php", +] +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.426865+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:79b4ea5b9dc7b4c587f7aca537c3ebb4f274c4bea713ec8d40a8ba2ce1e7189b" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/livewire__livewire-10747/tests/capture.py b/tasks/livewire__livewire-10747/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/livewire__livewire-10747/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/livewire__livewire-10747/tests/instruction.md b/tasks/livewire__livewire-10747/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..90b2d501b87dc86019155fc9473448e458112aab --- /dev/null +++ b/tasks/livewire__livewire-10747/tests/instruction.md @@ -0,0 +1,22 @@ +# Issue + +**Title:** [4.x] Fix `Form::resetErrorBag()` clearing the entire component error bag + +## Description + +Calling `resetErrorBag()` (or `resetValidation()` / `clearValidation()`) on a form object with no arguments wipes the entire component's error bag, not just the form's errors: + +```php +$this->addError('other', '...'); +$this->form->addError('title', '...'); + +$this->form->resetErrorBag(); // Also clears "other"... +``` + +This happens because the form passes an empty array to the component's `resetErrorBag()`, which treats an empty list as "clear everything". This PR resets `form.*` instead, so only that form's errors are cleared. Passing specific fields works the same as before. + +Note that a successful `$this->form->validate()` also calls `resetErrorBag()`, so it now only clears the form's own errors rather than every error on the component. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `f3b74902cf06`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10747/tests/oracle.patch b/tasks/livewire__livewire-10747/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..a99ee37efee001f230d3e5fec164e2912ba8fe99 --- /dev/null +++ b/tasks/livewire__livewire-10747/tests/oracle.patch @@ -0,0 +1,49 @@ +diff --git a/src/Features/SupportFormObjects/Form.php b/src/Features/SupportFormObjects/Form.php +index d1387640..a03c25ab 100644 +--- a/src/Features/SupportFormObjects/Form.php ++++ b/src/Features/SupportFormObjects/Form.php +@@ -83,7 +83,7 @@ class Form implements Arrayable + + public function resetErrorBag($field = null) + { +- $fields = (array) $field; ++ $fields = (array) ($field ?: '*'); + + foreach ($fields as $idx => $field) { + $fields[$idx] = $this->propertyName . '.' . $field; +diff --git a/src/Features/SupportFormObjects/UnitTest.php b/src/Features/SupportFormObjects/UnitTest.php +index f1568639..69bcb718 100644 +--- a/src/Features/SupportFormObjects/UnitTest.php ++++ b/src/Features/SupportFormObjects/UnitTest.php +@@ -1235,6 +1235,31 @@ class UnitTest extends \Tests\TestCase + ->assertOk(); + } + ++ public function test_resetting_a_forms_error_bag_only_clears_that_forms_errors() ++ { ++ Livewire::test(new class extends TestComponent { ++ public $other = ''; ++ ++ public PostFormStub $form; ++ ++ public function addErrors() ++ { ++ $this->addError('other', 'component error'); ++ $this->form->addError('title', 'form error'); ++ } ++ ++ public function clearFormErrors() ++ { ++ $this->form->resetErrorBag(); ++ } ++ }) ++ ->call('addErrors') ++ ->assertHasErrors(['other', 'form.title']) ++ ->call('clearFormErrors') ++ ->assertHasErrors(['other']) ++ ->assertHasNoErrors(['form.title']); ++ } ++ + public function test_can_reset_a_nested_form_property_from_the_component() + { + Livewire::test(new class extends TestComponent { diff --git a/tasks/livewire__livewire-10747/tests/test.sh b/tasks/livewire__livewire-10747/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..57dd7d5130d2c81a39d95c732d460092744c538a --- /dev/null +++ b/tasks/livewire__livewire-10747/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace f3b74902cf06647cd08a26847cd48ed9fbf6f424 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/livewire__livewire-10747/tests/verifier.py b/tasks/livewire__livewire-10747/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/livewire__livewire-10747/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/livewire__livewire-10750/environment/Dockerfile b/tasks/livewire__livewire-10750/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2b0e159ee8ce195ce98a086105e83d9d0bd84fd4 --- /dev/null +++ b/tasks/livewire__livewire-10750/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/livewire/livewire.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/livewire/livewire.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/livewire/livewire.git +WORKDIR /workspace +RUN git fetch --depth 1 origin d0b4e22841d362dd213ee9602c399594d387b6ee 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard d0b4e22841d362dd213ee9602c399594d387b6ee \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base d0b4e22841d362dd213ee9602c399594d387b6ee \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/livewire__livewire-10750/instruction.md b/tasks/livewire__livewire-10750/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8b2bb90aa705ce1b3f0f53fd8861ae1698c07b19 --- /dev/null +++ b/tasks/livewire__livewire-10750/instruction.md @@ -0,0 +1,23 @@ +# Issue + +**Title:** [4.x] Fix legacy models validation for encrypted model attributes + +## Description + +, a regression from #10559 in 4.4.2. + +#10559 made legacy model validation use the raw attribute instead of the cast value whenever the two differ, so input like `32.5` on an `integer` cast is no longer silently turned into `32` before validation. But casts like `encrypted` also store a different value in the attributes bag (the ciphertext), so those attributes are now validated against the encrypted string: + +```php +protected $casts = ['phone' => 'encrypted']; + +'contact.phone' => 'min:12|max:12' // Always fails, the ciphertext is too long... +``` + +This PR only uses the raw attribute when the cast value is an int or float coercion of it, which is the case #10559 was fixing. Every other cast is validated using its cast value again, like it was before 4.4.2. + +The tests cover both the encrypted case and the integer case from #10559. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d0b4e22841d3`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10750/solution/patch.diff b/tasks/livewire__livewire-10750/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..df39d2f414dda382561c3149cf4fc510db6c9ec6 --- /dev/null +++ b/tasks/livewire__livewire-10750/solution/patch.diff @@ -0,0 +1,100 @@ +diff --git a/src/Features/SupportLegacyModels/EloquentModelSynth.php b/src/Features/SupportLegacyModels/EloquentModelSynth.php +index 21ee7507..442ff19b 100644 +--- a/src/Features/SupportLegacyModels/EloquentModelSynth.php ++++ b/src/Features/SupportLegacyModels/EloquentModelSynth.php +@@ -104,10 +104,13 @@ class EloquentModelSynth extends Synth implements ArrayShapedSynth + + $casted = $values[$key]; + ++ if (! is_scalar($attribute) || $attribute == $casted) continue; ++ ++ // Integer and float casts coerce the raw input (e.g. "32.5" becomes 32), so validate the raw ++ // input instead. Other casts, like "encrypted", should be validated using the cast value... + if ( +- is_scalar($attribute) +- && is_scalar($casted) +- && $attribute != $casted ++ (is_int($casted) && (int) $attribute === $casted) ++ || (is_float($casted) && (float) $attribute === $casted) + ) { + $values[$key] = $attribute; + } +diff --git a/src/Features/SupportLegacyModels/Tests/EloquentModelValidationUnitTest.php b/src/Features/SupportLegacyModels/Tests/EloquentModelValidationUnitTest.php +index 78b39966..dbc2372d 100644 +--- a/src/Features/SupportLegacyModels/Tests/EloquentModelValidationUnitTest.php ++++ b/src/Features/SupportLegacyModels/Tests/EloquentModelValidationUnitTest.php +@@ -209,6 +209,24 @@ class EloquentModelValidationUnitTest extends \Tests\TestCase + + $this->assertEquals('sparkling', $cart->fresh()->items[0]->title); + } ++ ++ public function test_encrypted_model_attribute_is_validated_using_decrypted_value() ++ { ++ Livewire::test(ComponentWithCastedModelAttributes::class) ++ ->set('contact.phone', '111 111-1111') // 12 characters ++ ->call('save') ++ ->assertHasNoErrors('contact.phone') ++ ->set('contact.phone', '111') ++ ->call('save') ++ ->assertHasErrors(['contact.phone' => 'min:12']); ++ } ++ ++ public function test_integer_model_attribute_is_validated_using_raw_input() ++ { ++ Livewire::test(ComponentWithCastedModelAttributes::class) ++ ->call('saveAge', '32.5') ++ ->assertHasErrors(['contact.age' => 'integer']); ++ } + } + + class Foo extends Model +@@ -371,3 +389,49 @@ class ComponentForEloquentModelNestedHydrationMiddleware extends Component + return \view('dump-errors'); + } + } ++ ++class ContactWithCasts extends Model ++{ ++ use Sushi; ++ ++ protected $rows = [ ++ ['id' => 1, 'phone' => null, 'age' => 40], ++ ]; ++ ++ protected $casts = [ ++ 'phone' => 'encrypted', ++ 'age' => 'integer', ++ ]; ++} ++ ++class ComponentWithCastedModelAttributes extends Component ++{ ++ public ContactWithCasts $contact; ++ ++ protected $rules = [ ++ 'contact.phone' => 'nullable|min:12|max:12', ++ 'contact.age' => 'required|integer', ++ ]; ++ ++ public function mount() ++ { ++ $this->contact = ContactWithCasts::first(); ++ } ++ ++ public function save() ++ { ++ $this->validate(); ++ } ++ ++ public function saveAge($age) ++ { ++ $this->contact->age = $age; ++ ++ $this->validate(); ++ } ++ ++ public function render() ++ { ++ return \view('dump-errors'); ++ } ++} diff --git a/tasks/livewire__livewire-10750/solution/solve.sh b/tasks/livewire__livewire-10750/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/livewire__livewire-10750/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/livewire__livewire-10750/task.toml b/tasks/livewire__livewire-10750/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..78a21079dd244f39f24dbf8571afc0ffa3e6a475 --- /dev/null +++ b/tasks/livewire__livewire-10750/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/livewire__livewire-10750" +description = "[4.x] Fix legacy models validation for encrypted model attributes" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "livewire", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "livewire/livewire" +ref = "d0b4e22841d362dd213ee9602c399594d387b6ee" +reference = "https://github.com/livewire/livewire/pull/10750" +source_access = "auto" +built_at = "2026-11-16T16:09:51.388858+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:8b4f39ad44b5d49eacc501d583bc926c6adeed8237bd6571d76f8d339347064a" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-10-07T12:32:25Z" +diff_format = "unified" +context_files = [ + "src/Features/SupportLegacyModels/EloquentModelSynth.php", + "src/Features/SupportLegacyModels/Tests/EloquentModelValidationUnitTest.php", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 73 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.427408+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:108fd5bbaa619e83c7b309cc26c21beaddb12766fe0d939f64edd86f874f671a" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/livewire__livewire-10750/tests/capture.py b/tasks/livewire__livewire-10750/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/livewire__livewire-10750/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/livewire__livewire-10750/tests/instruction.md b/tasks/livewire__livewire-10750/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8b2bb90aa705ce1b3f0f53fd8861ae1698c07b19 --- /dev/null +++ b/tasks/livewire__livewire-10750/tests/instruction.md @@ -0,0 +1,23 @@ +# Issue + +**Title:** [4.x] Fix legacy models validation for encrypted model attributes + +## Description + +, a regression from #10559 in 4.4.2. + +#10559 made legacy model validation use the raw attribute instead of the cast value whenever the two differ, so input like `32.5` on an `integer` cast is no longer silently turned into `32` before validation. But casts like `encrypted` also store a different value in the attributes bag (the ciphertext), so those attributes are now validated against the encrypted string: + +```php +protected $casts = ['phone' => 'encrypted']; + +'contact.phone' => 'min:12|max:12' // Always fails, the ciphertext is too long... +``` + +This PR only uses the raw attribute when the cast value is an int or float coercion of it, which is the case #10559 was fixing. Every other cast is validated using its cast value again, like it was before 4.4.2. + +The tests cover both the encrypted case and the integer case from #10559. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d0b4e22841d3`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10750/tests/oracle.patch b/tasks/livewire__livewire-10750/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..df39d2f414dda382561c3149cf4fc510db6c9ec6 --- /dev/null +++ b/tasks/livewire__livewire-10750/tests/oracle.patch @@ -0,0 +1,100 @@ +diff --git a/src/Features/SupportLegacyModels/EloquentModelSynth.php b/src/Features/SupportLegacyModels/EloquentModelSynth.php +index 21ee7507..442ff19b 100644 +--- a/src/Features/SupportLegacyModels/EloquentModelSynth.php ++++ b/src/Features/SupportLegacyModels/EloquentModelSynth.php +@@ -104,10 +104,13 @@ class EloquentModelSynth extends Synth implements ArrayShapedSynth + + $casted = $values[$key]; + ++ if (! is_scalar($attribute) || $attribute == $casted) continue; ++ ++ // Integer and float casts coerce the raw input (e.g. "32.5" becomes 32), so validate the raw ++ // input instead. Other casts, like "encrypted", should be validated using the cast value... + if ( +- is_scalar($attribute) +- && is_scalar($casted) +- && $attribute != $casted ++ (is_int($casted) && (int) $attribute === $casted) ++ || (is_float($casted) && (float) $attribute === $casted) + ) { + $values[$key] = $attribute; + } +diff --git a/src/Features/SupportLegacyModels/Tests/EloquentModelValidationUnitTest.php b/src/Features/SupportLegacyModels/Tests/EloquentModelValidationUnitTest.php +index 78b39966..dbc2372d 100644 +--- a/src/Features/SupportLegacyModels/Tests/EloquentModelValidationUnitTest.php ++++ b/src/Features/SupportLegacyModels/Tests/EloquentModelValidationUnitTest.php +@@ -209,6 +209,24 @@ class EloquentModelValidationUnitTest extends \Tests\TestCase + + $this->assertEquals('sparkling', $cart->fresh()->items[0]->title); + } ++ ++ public function test_encrypted_model_attribute_is_validated_using_decrypted_value() ++ { ++ Livewire::test(ComponentWithCastedModelAttributes::class) ++ ->set('contact.phone', '111 111-1111') // 12 characters ++ ->call('save') ++ ->assertHasNoErrors('contact.phone') ++ ->set('contact.phone', '111') ++ ->call('save') ++ ->assertHasErrors(['contact.phone' => 'min:12']); ++ } ++ ++ public function test_integer_model_attribute_is_validated_using_raw_input() ++ { ++ Livewire::test(ComponentWithCastedModelAttributes::class) ++ ->call('saveAge', '32.5') ++ ->assertHasErrors(['contact.age' => 'integer']); ++ } + } + + class Foo extends Model +@@ -371,3 +389,49 @@ class ComponentForEloquentModelNestedHydrationMiddleware extends Component + return \view('dump-errors'); + } + } ++ ++class ContactWithCasts extends Model ++{ ++ use Sushi; ++ ++ protected $rows = [ ++ ['id' => 1, 'phone' => null, 'age' => 40], ++ ]; ++ ++ protected $casts = [ ++ 'phone' => 'encrypted', ++ 'age' => 'integer', ++ ]; ++} ++ ++class ComponentWithCastedModelAttributes extends Component ++{ ++ public ContactWithCasts $contact; ++ ++ protected $rules = [ ++ 'contact.phone' => 'nullable|min:12|max:12', ++ 'contact.age' => 'required|integer', ++ ]; ++ ++ public function mount() ++ { ++ $this->contact = ContactWithCasts::first(); ++ } ++ ++ public function save() ++ { ++ $this->validate(); ++ } ++ ++ public function saveAge($age) ++ { ++ $this->contact->age = $age; ++ ++ $this->validate(); ++ } ++ ++ public function render() ++ { ++ return \view('dump-errors'); ++ } ++} diff --git a/tasks/livewire__livewire-10750/tests/test.sh b/tasks/livewire__livewire-10750/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..f4255995d98bc2c91067af5b4e4a6a330f30ec75 --- /dev/null +++ b/tasks/livewire__livewire-10750/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace d0b4e22841d362dd213ee9602c399594d387b6ee > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/livewire__livewire-10750/tests/verifier.py b/tasks/livewire__livewire-10750/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/livewire__livewire-10750/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/livewire__livewire-10751/environment/Dockerfile b/tasks/livewire__livewire-10751/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a0b96c5c6f494298b60f115cb06e5bfc40abaad9 --- /dev/null +++ b/tasks/livewire__livewire-10751/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/livewire/livewire.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/livewire/livewire.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/livewire/livewire.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 3610890ab7e9f7de5b14e1cf5773298064a44e7a 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 3610890ab7e9f7de5b14e1cf5773298064a44e7a \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 3610890ab7e9f7de5b14e1cf5773298064a44e7a \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/livewire__livewire-10751/instruction.md b/tasks/livewire__livewire-10751/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..739a40c96835d02698f3d67c5ac6964c990c461c --- /dev/null +++ b/tasks/livewire__livewire-10751/instruction.md @@ -0,0 +1,23 @@ +# Issue + +**Title:** [4.x] Fix `validateOnly()` clearing unrelated validation errors + +## Description + +`validateOnly()` clears errors based on the matched *rule keys* rather than the field that was actually validated. This causes two problems after a full `validate()`: + +```php +public function updated($property) +{ + $this->validateOnly($property); +} +``` + +1. If the updated property has no rules (e.g. some UI state like `$step`), no rule keys match, `resetErrorBag([])` is called, and the **entire** error bag is wiped. +2. If the rule is a wildcard like `items.*.name`, validating `items.1.name` clears (or replaces) the errors for every `items.*.name`, not just row 1. + +This PR uses the validated `$field` when clearing or merging errors instead of the rule keys, so `validateOnly()` only ever touches the errors for the field it validated. Calling `validateOnly('items.*.name')` with a wildcard still affects every matching row, as before. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `3610890ab7e9`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10751/solution/patch.diff b/tasks/livewire__livewire-10751/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..0fcea15ede73d8ee67ba30af5836b3ae6dcd3a24 --- /dev/null +++ b/tasks/livewire__livewire-10751/solution/patch.diff @@ -0,0 +1,81 @@ +diff --git a/src/Features/SupportValidation/HandlesValidation.php b/src/Features/SupportValidation/HandlesValidation.php +index a0f1f6f5..2c8749b9 100644 +--- a/src/Features/SupportValidation/HandlesValidation.php ++++ b/src/Features/SupportValidation/HandlesValidation.php +@@ -371,8 +371,6 @@ trait HandlesValidation + + $rulesForField = $rulesForField->toArray(); + +- $ruleKeysForField = array_keys($rulesForField); +- + $data = array_merge($this->getDataForValidation($rules), $dataOverrides); + + $data = $this->prepareForValidation($data); +@@ -415,13 +413,13 @@ trait HandlesValidation + $messages = $e->validator->getMessageBag(); + + invade($e->validator)->messages = $messages->merge( +- $this->errorBagExcept($ruleKeysForField) ++ $this->errorBagExcept($field) + ); + + throw $e; + } + +- $this->resetErrorBag($ruleKeysForField); ++ $this->resetErrorBag($field); + + return $result; + } +diff --git a/src/Features/SupportValidation/UnitTest.php b/src/Features/SupportValidation/UnitTest.php +index ab2199cf..012ee935 100644 +--- a/src/Features/SupportValidation/UnitTest.php ++++ b/src/Features/SupportValidation/UnitTest.php +@@ -1304,6 +1304,47 @@ class UnitTest extends \Tests\TestCase + $this->assertSame(1, ValidationUnwrappingSpyCollection::$toArrayCalls); + } + ++ public function test_validate_only_on_a_field_without_rules_does_not_clear_other_errors() ++ { ++ Livewire::test(new class extends TestComponent { ++ public $email = ''; ++ public $step = 1; ++ ++ protected $rules = ['email' => 'required']; ++ ++ public function save() ++ { ++ $this->validate(); ++ } ++ ++ public function updated($property) ++ { ++ $this->validateOnly($property); ++ } ++ }) ++ ->call('save') ++ ->assertHasErrors('email') ++ ->set('step', 2) ++ ->assertHasErrors('email'); ++ } ++ ++ public function test_validate_only_on_a_nested_field_does_not_clear_errors_on_its_siblings() ++ { ++ Livewire::test(ForValidation::class) ++ ->set('items', [ ++ ['foo' => 'bar', 'baz' => ''], ++ ['foo' => 'bar', 'baz' => ''], ++ ]) ++ ->call('runDeeplyNestedValidation') ++ ->assertHasErrors(['items.0.baz', 'items.1.baz']) ++ ->call('runDeeplyNestedValidationOnly', 'items.1.baz') ++ ->assertHasErrors(['items.0.baz', 'items.1.baz']) ++ ->set('items.1.baz', 'fixed') ++ ->call('runDeeplyNestedValidationOnly', 'items.1.baz') ++ ->assertHasErrors('items.0.baz') ++ ->assertHasNoErrors('items.1.baz'); ++ } ++ + public function test_validate_only_with_a_wildcard_field_only_validates_the_targeted_keys_in_each_item() + { + Livewire::test(new class extends TestComponent { diff --git a/tasks/livewire__livewire-10751/solution/solve.sh b/tasks/livewire__livewire-10751/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/livewire__livewire-10751/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/livewire__livewire-10751/task.toml b/tasks/livewire__livewire-10751/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..47a4bc5bd06861bbbaaef63e412551490224a2ca --- /dev/null +++ b/tasks/livewire__livewire-10751/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/livewire__livewire-10751" +description = "[4.x] Fix `validateOnly()` clearing unrelated validation errors" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "livewire", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "livewire/livewire" +ref = "3610890ab7e9f7de5b14e1cf5773298064a44e7a" +reference = "https://github.com/livewire/livewire/pull/10751" +source_access = "auto" +built_at = "2026-11-16T16:09:51.414565+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:73e62950288e9ed52f74227e75fc0f5b32fd5a5263b54c596ce40807d7058c51" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-10-07T12:29:39Z" +diff_format = "unified" +context_files = [ + "src/Features/SupportValidation/HandlesValidation.php", + "src/Features/SupportValidation/UnitTest.php", +] +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.427973+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:2bdc8dfa4efdcdf0e136f35854eca2ac405070049a04331a0ddfa623f5592ec2" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/livewire__livewire-10751/tests/capture.py b/tasks/livewire__livewire-10751/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/livewire__livewire-10751/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/livewire__livewire-10751/tests/instruction.md b/tasks/livewire__livewire-10751/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..739a40c96835d02698f3d67c5ac6964c990c461c --- /dev/null +++ b/tasks/livewire__livewire-10751/tests/instruction.md @@ -0,0 +1,23 @@ +# Issue + +**Title:** [4.x] Fix `validateOnly()` clearing unrelated validation errors + +## Description + +`validateOnly()` clears errors based on the matched *rule keys* rather than the field that was actually validated. This causes two problems after a full `validate()`: + +```php +public function updated($property) +{ + $this->validateOnly($property); +} +``` + +1. If the updated property has no rules (e.g. some UI state like `$step`), no rule keys match, `resetErrorBag([])` is called, and the **entire** error bag is wiped. +2. If the rule is a wildcard like `items.*.name`, validating `items.1.name` clears (or replaces) the errors for every `items.*.name`, not just row 1. + +This PR uses the validated `$field` when clearing or merging errors instead of the rule keys, so `validateOnly()` only ever touches the errors for the field it validated. Calling `validateOnly('items.*.name')` with a wildcard still affects every matching row, as before. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `3610890ab7e9`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10751/tests/oracle.patch b/tasks/livewire__livewire-10751/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..0fcea15ede73d8ee67ba30af5836b3ae6dcd3a24 --- /dev/null +++ b/tasks/livewire__livewire-10751/tests/oracle.patch @@ -0,0 +1,81 @@ +diff --git a/src/Features/SupportValidation/HandlesValidation.php b/src/Features/SupportValidation/HandlesValidation.php +index a0f1f6f5..2c8749b9 100644 +--- a/src/Features/SupportValidation/HandlesValidation.php ++++ b/src/Features/SupportValidation/HandlesValidation.php +@@ -371,8 +371,6 @@ trait HandlesValidation + + $rulesForField = $rulesForField->toArray(); + +- $ruleKeysForField = array_keys($rulesForField); +- + $data = array_merge($this->getDataForValidation($rules), $dataOverrides); + + $data = $this->prepareForValidation($data); +@@ -415,13 +413,13 @@ trait HandlesValidation + $messages = $e->validator->getMessageBag(); + + invade($e->validator)->messages = $messages->merge( +- $this->errorBagExcept($ruleKeysForField) ++ $this->errorBagExcept($field) + ); + + throw $e; + } + +- $this->resetErrorBag($ruleKeysForField); ++ $this->resetErrorBag($field); + + return $result; + } +diff --git a/src/Features/SupportValidation/UnitTest.php b/src/Features/SupportValidation/UnitTest.php +index ab2199cf..012ee935 100644 +--- a/src/Features/SupportValidation/UnitTest.php ++++ b/src/Features/SupportValidation/UnitTest.php +@@ -1304,6 +1304,47 @@ class UnitTest extends \Tests\TestCase + $this->assertSame(1, ValidationUnwrappingSpyCollection::$toArrayCalls); + } + ++ public function test_validate_only_on_a_field_without_rules_does_not_clear_other_errors() ++ { ++ Livewire::test(new class extends TestComponent { ++ public $email = ''; ++ public $step = 1; ++ ++ protected $rules = ['email' => 'required']; ++ ++ public function save() ++ { ++ $this->validate(); ++ } ++ ++ public function updated($property) ++ { ++ $this->validateOnly($property); ++ } ++ }) ++ ->call('save') ++ ->assertHasErrors('email') ++ ->set('step', 2) ++ ->assertHasErrors('email'); ++ } ++ ++ public function test_validate_only_on_a_nested_field_does_not_clear_errors_on_its_siblings() ++ { ++ Livewire::test(ForValidation::class) ++ ->set('items', [ ++ ['foo' => 'bar', 'baz' => ''], ++ ['foo' => 'bar', 'baz' => ''], ++ ]) ++ ->call('runDeeplyNestedValidation') ++ ->assertHasErrors(['items.0.baz', 'items.1.baz']) ++ ->call('runDeeplyNestedValidationOnly', 'items.1.baz') ++ ->assertHasErrors(['items.0.baz', 'items.1.baz']) ++ ->set('items.1.baz', 'fixed') ++ ->call('runDeeplyNestedValidationOnly', 'items.1.baz') ++ ->assertHasErrors('items.0.baz') ++ ->assertHasNoErrors('items.1.baz'); ++ } ++ + public function test_validate_only_with_a_wildcard_field_only_validates_the_targeted_keys_in_each_item() + { + Livewire::test(new class extends TestComponent { diff --git a/tasks/livewire__livewire-10751/tests/test.sh b/tasks/livewire__livewire-10751/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..21478f1950826e692271b230e93e89112d63630b --- /dev/null +++ b/tasks/livewire__livewire-10751/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 3610890ab7e9f7de5b14e1cf5773298064a44e7a > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/livewire__livewire-10751/tests/verifier.py b/tasks/livewire__livewire-10751/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/livewire__livewire-10751/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/livewire__livewire-10753/environment/Dockerfile b/tasks/livewire__livewire-10753/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..05da7619a4c1b9cd5ace748e4a9eb39d737fd5bb --- /dev/null +++ b/tasks/livewire__livewire-10753/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/livewire/livewire.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/livewire/livewire.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/livewire/livewire.git +WORKDIR /workspace +RUN git fetch --depth 1 origin ada5a07830c7a6a5bce2272ceea38259482d04a0 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard ada5a07830c7a6a5bce2272ceea38259482d04a0 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base ada5a07830c7a6a5bce2272ceea38259482d04a0 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/livewire__livewire-10753/instruction.md b/tasks/livewire__livewire-10753/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b8b0e2322d191f2c3c5a8d3bf1c3b54a90665835 --- /dev/null +++ b/tasks/livewire__livewire-10753/instruction.md @@ -0,0 +1,21 @@ +# Issue + +**Title:** [4.x] Don't read uninitialized typed properties when setting a nested update path + +## Description + +. . + +A typed public property that's never assigned is still uninitialized on the next request. For a nested update like `name.first`, `updateProperty()` reads `$component->name` before drilling into it, and that read throws `Error: must not be accessed before initialization`. Since it isn't a `TypeError`, a tampered update comes back as a reported 500 instead of the quiet 419 Livewire returns for other malformed updates. + +```php +public string $name; + +// POST updates: ['name.first' => 'Caleb'] -> 500 +``` + +This PR starts from an empty array when the property is typed and uninitialized, the same way `recursivelySetValue()` already builds missing nested keys. The assignment then goes through `setComponentPropertyAwareOfTypes()`, which throws a `TypeError` in debug mode and aborts with a 419 otherwise. #10687 fixed the same read in `expandConsolidatedFormObjectUpdates()`. This fixes the other place it happens. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `ada5a07830c7`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10753/solution/patch.diff b/tasks/livewire__livewire-10753/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..b5bd3b0593861a8a102c175e6e15e7273aa95f48 --- /dev/null +++ b/tasks/livewire__livewire-10753/solution/patch.diff @@ -0,0 +1,61 @@ +diff --git a/src/Mechanisms/HandleComponents/HandleComponents.php b/src/Mechanisms/HandleComponents/HandleComponents.php +index 1e274ac3..e5f929f3 100644 +--- a/src/Mechanisms/HandleComponents/HandleComponents.php ++++ b/src/Mechanisms/HandleComponents/HandleComponents.php +@@ -455,7 +455,12 @@ class HandleComponents extends Mechanism + if (empty($segments)) { + $this->setComponentPropertyAwareOfTypes($component, $property, $value); + } else { +- $propertyValue = $component->$property; ++ // An uninitialized typed property has no value to drill into. Start from ++ // an empty structure, like missing nested keys below, so the assignment ++ // runs through the usual typed property handling instead of throwing... ++ $propertyValue = Utils::propertyIsTypedAndUninitialized($component, $property) ++ ? [] ++ : $component->$property; + + $this->setComponentPropertyAwareOfTypes($component, $property, + $this->recursivelySetValue($property, $propertyValue, $value, $segments, 0, $context) +diff --git a/src/Mechanisms/HandleComponents/UnitTest.php b/src/Mechanisms/HandleComponents/UnitTest.php +index e82bce6f..e8ee6c21 100644 +--- a/src/Mechanisms/HandleComponents/UnitTest.php ++++ b/src/Mechanisms/HandleComponents/UnitTest.php +@@ -271,6 +271,38 @@ class UnitTest extends \Tests\TestCase + ->assertSetStrict('refreshed', true); + } + ++ public function test_nested_update_to_uninitialized_typed_property_returns_419_when_debug_is_disabled() ++ { ++ config()->set('app.debug', false); ++ ++ $component = Livewire::test(new class extends TestComponent { ++ public string $name; ++ }); ++ ++ $response = $this->withHeaders(['X-Livewire' => 'true']) ++ ->postJson(EndpointResolver::updatePath(), ['components' => [ ++ [ ++ 'snapshot' => json_encode($component->snapshot), ++ 'updates' => ['name.first' => 'Caleb'], ++ 'calls' => [], ++ ], ++ ]]); ++ ++ $response->assertStatus(419); ++ } ++ ++ public function test_nested_update_to_uninitialized_typed_property_throws_type_error_when_debug_is_enabled() ++ { ++ config()->set('app.debug', true); ++ ++ $this->expectException(\TypeError::class); ++ ++ Livewire::test(new class extends TestComponent { ++ public string $name; ++ }) ++ ->set('name.first', 'Caleb'); ++ } ++ + public function test_invalid_call_method_name_returns_419_when_debug_is_disabled() + { + config()->set('app.debug', false); diff --git a/tasks/livewire__livewire-10753/solution/solve.sh b/tasks/livewire__livewire-10753/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/livewire__livewire-10753/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/livewire__livewire-10753/task.toml b/tasks/livewire__livewire-10753/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..5be762aadc819049660aa3567afc90f8976be039 --- /dev/null +++ b/tasks/livewire__livewire-10753/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/livewire__livewire-10753" +description = "[4.x] Don't read uninitialized typed properties when setting a nested update path" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "livewire", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "livewire/livewire" +ref = "ada5a07830c7a6a5bce2272ceea38259482d04a0" +reference = "https://github.com/livewire/livewire/pull/10753" +source_access = "auto" +built_at = "2026-11-16T16:09:51.434231+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:a8e4b490b3ba526947299e10e548f03974ae6cf632d85698bc7e98c8c073a6f3" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-10-07T11:44:30Z" +diff_format = "unified" +context_files = [ + "src/Mechanisms/HandleComponents/HandleComponents.php", + "src/Mechanisms/HandleComponents/UnitTest.php", +] +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.428559+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:a91ba79859437a95bf2efd6b6721dda335fd6f0943787de03cd1bc1f178e31c3" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/livewire__livewire-10753/tests/capture.py b/tasks/livewire__livewire-10753/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/livewire__livewire-10753/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/livewire__livewire-10753/tests/instruction.md b/tasks/livewire__livewire-10753/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b8b0e2322d191f2c3c5a8d3bf1c3b54a90665835 --- /dev/null +++ b/tasks/livewire__livewire-10753/tests/instruction.md @@ -0,0 +1,21 @@ +# Issue + +**Title:** [4.x] Don't read uninitialized typed properties when setting a nested update path + +## Description + +. . + +A typed public property that's never assigned is still uninitialized on the next request. For a nested update like `name.first`, `updateProperty()` reads `$component->name` before drilling into it, and that read throws `Error: must not be accessed before initialization`. Since it isn't a `TypeError`, a tampered update comes back as a reported 500 instead of the quiet 419 Livewire returns for other malformed updates. + +```php +public string $name; + +// POST updates: ['name.first' => 'Caleb'] -> 500 +``` + +This PR starts from an empty array when the property is typed and uninitialized, the same way `recursivelySetValue()` already builds missing nested keys. The assignment then goes through `setComponentPropertyAwareOfTypes()`, which throws a `TypeError` in debug mode and aborts with a 419 otherwise. #10687 fixed the same read in `expandConsolidatedFormObjectUpdates()`. This fixes the other place it happens. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `ada5a07830c7`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10753/tests/oracle.patch b/tasks/livewire__livewire-10753/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..b5bd3b0593861a8a102c175e6e15e7273aa95f48 --- /dev/null +++ b/tasks/livewire__livewire-10753/tests/oracle.patch @@ -0,0 +1,61 @@ +diff --git a/src/Mechanisms/HandleComponents/HandleComponents.php b/src/Mechanisms/HandleComponents/HandleComponents.php +index 1e274ac3..e5f929f3 100644 +--- a/src/Mechanisms/HandleComponents/HandleComponents.php ++++ b/src/Mechanisms/HandleComponents/HandleComponents.php +@@ -455,7 +455,12 @@ class HandleComponents extends Mechanism + if (empty($segments)) { + $this->setComponentPropertyAwareOfTypes($component, $property, $value); + } else { +- $propertyValue = $component->$property; ++ // An uninitialized typed property has no value to drill into. Start from ++ // an empty structure, like missing nested keys below, so the assignment ++ // runs through the usual typed property handling instead of throwing... ++ $propertyValue = Utils::propertyIsTypedAndUninitialized($component, $property) ++ ? [] ++ : $component->$property; + + $this->setComponentPropertyAwareOfTypes($component, $property, + $this->recursivelySetValue($property, $propertyValue, $value, $segments, 0, $context) +diff --git a/src/Mechanisms/HandleComponents/UnitTest.php b/src/Mechanisms/HandleComponents/UnitTest.php +index e82bce6f..e8ee6c21 100644 +--- a/src/Mechanisms/HandleComponents/UnitTest.php ++++ b/src/Mechanisms/HandleComponents/UnitTest.php +@@ -271,6 +271,38 @@ class UnitTest extends \Tests\TestCase + ->assertSetStrict('refreshed', true); + } + ++ public function test_nested_update_to_uninitialized_typed_property_returns_419_when_debug_is_disabled() ++ { ++ config()->set('app.debug', false); ++ ++ $component = Livewire::test(new class extends TestComponent { ++ public string $name; ++ }); ++ ++ $response = $this->withHeaders(['X-Livewire' => 'true']) ++ ->postJson(EndpointResolver::updatePath(), ['components' => [ ++ [ ++ 'snapshot' => json_encode($component->snapshot), ++ 'updates' => ['name.first' => 'Caleb'], ++ 'calls' => [], ++ ], ++ ]]); ++ ++ $response->assertStatus(419); ++ } ++ ++ public function test_nested_update_to_uninitialized_typed_property_throws_type_error_when_debug_is_enabled() ++ { ++ config()->set('app.debug', true); ++ ++ $this->expectException(\TypeError::class); ++ ++ Livewire::test(new class extends TestComponent { ++ public string $name; ++ }) ++ ->set('name.first', 'Caleb'); ++ } ++ + public function test_invalid_call_method_name_returns_419_when_debug_is_disabled() + { + config()->set('app.debug', false); diff --git a/tasks/livewire__livewire-10753/tests/test.sh b/tasks/livewire__livewire-10753/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..4480f9890d6d694c073d5719e658f54374a9ce8a --- /dev/null +++ b/tasks/livewire__livewire-10753/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace ada5a07830c7a6a5bce2272ceea38259482d04a0 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/livewire__livewire-10753/tests/verifier.py b/tasks/livewire__livewire-10753/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/livewire__livewire-10753/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/livewire__livewire-10754/environment/Dockerfile b/tasks/livewire__livewire-10754/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..05da7619a4c1b9cd5ace748e4a9eb39d737fd5bb --- /dev/null +++ b/tasks/livewire__livewire-10754/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/livewire/livewire.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/livewire/livewire.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/livewire/livewire.git +WORKDIR /workspace +RUN git fetch --depth 1 origin ada5a07830c7a6a5bce2272ceea38259482d04a0 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard ada5a07830c7a6a5bce2272ceea38259482d04a0 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base ada5a07830c7a6a5bce2272ceea38259482d04a0 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/livewire__livewire-10754/instruction.md b/tasks/livewire__livewire-10754/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..44872315b324ff8657badcbcfa6ce2c775b274b6 --- /dev/null +++ b/tasks/livewire__livewire-10754/instruction.md @@ -0,0 +1,22 @@ +# Issue + +**Title:** [4.x] Only report locked property violations in debug mode + +## Description + +Writing to a `#[Locked]` property can only happen with a tampered request. Since #9970, `CannotUpdateLockedPropertyException` renders a quiet 419 outside of debug mode, but it's still reported, so every scanner probing a locked property shows up in Sentry / Flare / Slack as an application error with nothing to fix. + +This applies the same treatment #10690 gave `MethodNotFoundException`: the exception is only reported when `app.debug` is on. + +```php +public function report(): bool +{ + return ! config('app.debug'); +} +``` + +Locally and in tests the exception is still reported and rendered in full, so an honest mistake like `wire:model` on a locked property stays loud where you'd notice it. In production it's a quiet 419 like the other probe responses. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `ada5a07830c7`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10754/solution/patch.diff b/tasks/livewire__livewire-10754/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..7dd142528a52e55afb0509d712f5f077d60b28f4 --- /dev/null +++ b/tasks/livewire__livewire-10754/solution/patch.diff @@ -0,0 +1,69 @@ +diff --git a/src/Features/SupportLockedProperties/CannotUpdateLockedPropertyException.php b/src/Features/SupportLockedProperties/CannotUpdateLockedPropertyException.php +index 2174b718..9871bb50 100644 +--- a/src/Features/SupportLockedProperties/CannotUpdateLockedPropertyException.php ++++ b/src/Features/SupportLockedProperties/CannotUpdateLockedPropertyException.php +@@ -11,6 +11,11 @@ class CannotUpdateLockedPropertyException extends \Exception + ); + } + ++ public function report(): bool ++ { ++ return ! config('app.debug'); ++ } ++ + // In debug mode, let Laravel render the full error page. + // In production, return a generic 419 to avoid leaking details. + public function render($request) +diff --git a/src/Features/SupportLockedProperties/UnitTest.php b/src/Features/SupportLockedProperties/UnitTest.php +index d29569c0..8be92440 100644 +--- a/src/Features/SupportLockedProperties/UnitTest.php ++++ b/src/Features/SupportLockedProperties/UnitTest.php +@@ -2,6 +2,7 @@ + + namespace Livewire\Features\SupportLockedProperties; + ++use Illuminate\Contracts\Debug\ExceptionHandler; + use Livewire\Livewire; + use Livewire\Component as BaseComponent; + use Livewire\Form; +@@ -95,6 +96,40 @@ class UnitTest extends \Tests\TestCase + + $response->assertStatus(419); + } ++ ++ function test_locked_property_exception_is_not_reported_when_debug_is_disabled() ++ { ++ config()->set('app.debug', false); ++ ++ $reported = []; ++ app(ExceptionHandler::class) ++ ->reportable(function (CannotUpdateLockedPropertyException $e) use (&$reported) { ++ $reported[] = $e; ++ ++ return false; ++ }); ++ ++ app(ExceptionHandler::class)->report(new CannotUpdateLockedPropertyException('count')); ++ ++ $this->assertEmpty($reported); ++ } ++ ++ function test_locked_property_exception_is_reported_when_debug_is_enabled() ++ { ++ config()->set('app.debug', true); ++ ++ $reported = []; ++ app(ExceptionHandler::class) ++ ->reportable(function (CannotUpdateLockedPropertyException $e) use (&$reported) { ++ $reported[] = $e; ++ ++ return false; ++ }); ++ ++ app(ExceptionHandler::class)->report(new CannotUpdateLockedPropertyException('count')); ++ ++ $this->assertCount(1, $reported); ++ } + } + + class SomeForm extends Form { diff --git a/tasks/livewire__livewire-10754/solution/solve.sh b/tasks/livewire__livewire-10754/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/livewire__livewire-10754/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/livewire__livewire-10754/task.toml b/tasks/livewire__livewire-10754/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..e42ca502f07eeaba80c5ffc99f8371e08fa195d2 --- /dev/null +++ b/tasks/livewire__livewire-10754/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/livewire__livewire-10754" +description = "[4.x] Only report locked property violations in debug mode" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "livewire", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "livewire/livewire" +ref = "ada5a07830c7a6a5bce2272ceea38259482d04a0" +reference = "https://github.com/livewire/livewire/pull/10754" +source_access = "auto" +built_at = "2026-11-16T16:09:51.435950+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:dfe3bd44897994d58d4e3e61e31335d68cf36015bfd739117a4ecd843678f493" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-10-07T11:42:48Z" +diff_format = "unified" +context_files = [ + "src/Features/SupportLockedProperties/CannotUpdateLockedPropertyException.php", + "src/Features/SupportLockedProperties/UnitTest.php", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 40 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.429143+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:a91ba79859437a95bf2efd6b6721dda335fd6f0943787de03cd1bc1f178e31c3" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/livewire__livewire-10754/tests/capture.py b/tasks/livewire__livewire-10754/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/livewire__livewire-10754/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/livewire__livewire-10754/tests/instruction.md b/tasks/livewire__livewire-10754/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..44872315b324ff8657badcbcfa6ce2c775b274b6 --- /dev/null +++ b/tasks/livewire__livewire-10754/tests/instruction.md @@ -0,0 +1,22 @@ +# Issue + +**Title:** [4.x] Only report locked property violations in debug mode + +## Description + +Writing to a `#[Locked]` property can only happen with a tampered request. Since #9970, `CannotUpdateLockedPropertyException` renders a quiet 419 outside of debug mode, but it's still reported, so every scanner probing a locked property shows up in Sentry / Flare / Slack as an application error with nothing to fix. + +This applies the same treatment #10690 gave `MethodNotFoundException`: the exception is only reported when `app.debug` is on. + +```php +public function report(): bool +{ + return ! config('app.debug'); +} +``` + +Locally and in tests the exception is still reported and rendered in full, so an honest mistake like `wire:model` on a locked property stays loud where you'd notice it. In production it's a quiet 419 like the other probe responses. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `ada5a07830c7`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10754/tests/oracle.patch b/tasks/livewire__livewire-10754/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..7dd142528a52e55afb0509d712f5f077d60b28f4 --- /dev/null +++ b/tasks/livewire__livewire-10754/tests/oracle.patch @@ -0,0 +1,69 @@ +diff --git a/src/Features/SupportLockedProperties/CannotUpdateLockedPropertyException.php b/src/Features/SupportLockedProperties/CannotUpdateLockedPropertyException.php +index 2174b718..9871bb50 100644 +--- a/src/Features/SupportLockedProperties/CannotUpdateLockedPropertyException.php ++++ b/src/Features/SupportLockedProperties/CannotUpdateLockedPropertyException.php +@@ -11,6 +11,11 @@ class CannotUpdateLockedPropertyException extends \Exception + ); + } + ++ public function report(): bool ++ { ++ return ! config('app.debug'); ++ } ++ + // In debug mode, let Laravel render the full error page. + // In production, return a generic 419 to avoid leaking details. + public function render($request) +diff --git a/src/Features/SupportLockedProperties/UnitTest.php b/src/Features/SupportLockedProperties/UnitTest.php +index d29569c0..8be92440 100644 +--- a/src/Features/SupportLockedProperties/UnitTest.php ++++ b/src/Features/SupportLockedProperties/UnitTest.php +@@ -2,6 +2,7 @@ + + namespace Livewire\Features\SupportLockedProperties; + ++use Illuminate\Contracts\Debug\ExceptionHandler; + use Livewire\Livewire; + use Livewire\Component as BaseComponent; + use Livewire\Form; +@@ -95,6 +96,40 @@ class UnitTest extends \Tests\TestCase + + $response->assertStatus(419); + } ++ ++ function test_locked_property_exception_is_not_reported_when_debug_is_disabled() ++ { ++ config()->set('app.debug', false); ++ ++ $reported = []; ++ app(ExceptionHandler::class) ++ ->reportable(function (CannotUpdateLockedPropertyException $e) use (&$reported) { ++ $reported[] = $e; ++ ++ return false; ++ }); ++ ++ app(ExceptionHandler::class)->report(new CannotUpdateLockedPropertyException('count')); ++ ++ $this->assertEmpty($reported); ++ } ++ ++ function test_locked_property_exception_is_reported_when_debug_is_enabled() ++ { ++ config()->set('app.debug', true); ++ ++ $reported = []; ++ app(ExceptionHandler::class) ++ ->reportable(function (CannotUpdateLockedPropertyException $e) use (&$reported) { ++ $reported[] = $e; ++ ++ return false; ++ }); ++ ++ app(ExceptionHandler::class)->report(new CannotUpdateLockedPropertyException('count')); ++ ++ $this->assertCount(1, $reported); ++ } + } + + class SomeForm extends Form { diff --git a/tasks/livewire__livewire-10754/tests/test.sh b/tasks/livewire__livewire-10754/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..4480f9890d6d694c073d5719e658f54374a9ce8a --- /dev/null +++ b/tasks/livewire__livewire-10754/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace ada5a07830c7a6a5bce2272ceea38259482d04a0 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/livewire__livewire-10754/tests/verifier.py b/tasks/livewire__livewire-10754/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/livewire__livewire-10754/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/livewire__livewire-10758/environment/Dockerfile b/tasks/livewire__livewire-10758/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2b0e159ee8ce195ce98a086105e83d9d0bd84fd4 --- /dev/null +++ b/tasks/livewire__livewire-10758/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/livewire/livewire.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/livewire/livewire.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/livewire/livewire.git +WORKDIR /workspace +RUN git fetch --depth 1 origin d0b4e22841d362dd213ee9602c399594d387b6ee 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard d0b4e22841d362dd213ee9602c399594d387b6ee \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base d0b4e22841d362dd213ee9602c399594d387b6ee \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/livewire__livewire-10758/instruction.md b/tasks/livewire__livewire-10758/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..06e04993614c12800437bb4737d66cb3bf168114 --- /dev/null +++ b/tasks/livewire__livewire-10758/instruction.md @@ -0,0 +1,28 @@ +# Issue + +**Title:** [4.x] Fix interceptor unsubscribe functions removing the wrong interceptor or throwing + +## Description + +Interceptor unsubscribe functions remove their callback with `splice(indexOf(callback), 1)`. If the callback is already gone, `indexOf()` returns `-1` and `splice(-1, 1)` removes whichever interceptor was registered last: + +```js +let unsubscribe = $wire.intercept(() => { /* first */ }) + +$wire.intercept(() => { /* second */ }) + +unsubscribe() +unsubscribe() // Removes "second"... +``` + +Separately, the unsubscribe returned by `$wire.interceptMessage()` calls `WeakBag::delete()`, which doesn't exist, so it throws and never removes anything. + +This PR adds a tiny `arrayPull(array, item)` helper that only splices when the item is present, and uses it in every interceptor unsubscribe (and in `Component::addCleanup()`, which already did this check by hand). Component message interceptors now pull their own callback from the component's list. + +Two browser tests cover both cases and fail without the fix. + +Pairs with #10759 (same area, no conflicts between them). + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d0b4e22841d3`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10758/solution/patch.diff b/tasks/livewire__livewire-10758/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..8cf58a8bd887913766bdf83fe16795ff7f3677cd --- /dev/null +++ b/tasks/livewire__livewire-10758/solution/patch.diff @@ -0,0 +1,175 @@ +diff --git a/js/component.js b/js/component.js +index 804733a7..57f422c9 100644 +--- a/js/component.js ++++ b/js/component.js +@@ -1,4 +1,4 @@ +-import { dataSet, deepClone, diff, diffAndConsolidate, diffAndPatchRecursive, extractData} from '@/utils' ++import { arrayPull, dataSet, deepClone, diff, diffAndConsolidate, diffAndPatchRecursive, extractData} from '@/utils' + import { generateWireObject } from '@/$wire' + import { findComponentByEl, findComponent, hasComponent } from '@/store' + import { trigger } from '@/hooks' +@@ -324,11 +324,7 @@ export class Component { + this.cleanups.push(cleanup) + + return () => { +- let index = this.cleanups.indexOf(cleanup) +- +- if (index === -1) return +- +- this.cleanups.splice(index, 1) ++ arrayPull(this.cleanups, cleanup) + } + } + +diff --git a/js/request/index.js b/js/request/index.js +index 26279906..0e22415d 100644 +--- a/js/request/index.js ++++ b/js/request/index.js +@@ -1,4 +1,4 @@ +-import { getCsrfToken, contentIsFromDump, splitDumpFromContent, getUpdateUri } from '@/utils' ++import { arrayPull, getCsrfToken, contentIsFromDump, splitDumpFromContent, getUpdateUri } from '@/utils' + import { coordinateNetworkInteractions } from './interactions.js' + import { MessageRequest, PageRequest } from './request.js' + import { InterceptorRegistry } from './interceptor.js' +@@ -37,7 +37,7 @@ export function interceptAction(callback) { + actionInterceptors.push(callback) + + return () => { +- actionInterceptors.splice(actionInterceptors.indexOf(callback), 1) ++ arrayPull(actionInterceptors, callback) + } + } + +@@ -53,7 +53,7 @@ export function interceptPartition(callback) { + partitionInterceptors.push(callback) + + return () => { +- partitionInterceptors.splice(partitionInterceptors.indexOf(callback), 1) ++ arrayPull(partitionInterceptors, callback) + } + } + +diff --git a/js/request/interceptor.js b/js/request/interceptor.js +index df2df69b..10534393 100644 +--- a/js/request/interceptor.js ++++ b/js/request/interceptor.js +@@ -1,4 +1,4 @@ +-import { WeakBag } from "@/utils" ++import { arrayPull, WeakBag } from "@/utils" + + export class MessageInterceptor { + onSend = () => {} +@@ -95,7 +95,7 @@ export class InterceptorRegistry { + this.messageInterceptorCallbacksByComponent.add(component, callback) + + return () => { +- this.messageInterceptorCallbacksByComponent.delete(component, callback) ++ arrayPull(this.messageInterceptorCallbacksByComponent.get(component), callback) + } + } + +@@ -103,7 +103,7 @@ export class InterceptorRegistry { + this.messageInterceptorCallbacks.push(callback) + + return () => { +- this.messageInterceptorCallbacks.splice(this.messageInterceptorCallbacks.indexOf(callback), 1) ++ arrayPull(this.messageInterceptorCallbacks, callback) + } + } + +@@ -111,7 +111,7 @@ export class InterceptorRegistry { + this.requestInterceptorCallbacks.push(callback) + + return () => { +- this.requestInterceptorCallbacks.splice(this.requestInterceptorCallbacks.indexOf(callback), 1) ++ arrayPull(this.requestInterceptorCallbacks, callback) + } + } + +diff --git a/js/utils.js b/js/utils.js +index 0a85f6aa..60ba65cd 100644 +--- a/js/utils.js ++++ b/js/utils.js +@@ -33,6 +33,12 @@ export class WeakBag { + each(key, callback) { return this.get(key).forEach(callback) } + } + ++export function arrayPull(array, item) { ++ let index = array.indexOf(item) ++ ++ if (index !== -1) array.splice(index, 1) ++} ++ + export function dispatch(target, name, detail = {}, bubbles = true) { + target.dispatchEvent( + new CustomEvent(name, { +diff --git a/src/Features/SupportInterceptors/BrowserTest.php b/src/Features/SupportInterceptors/BrowserTest.php +index c32f7145..00fdf3f2 100644 +--- a/src/Features/SupportInterceptors/BrowserTest.php ++++ b/src/Features/SupportInterceptors/BrowserTest.php +@@ -706,4 +706,65 @@ class BrowserTest extends \Tests\BrowserTestCase + ->assertSeeIn('@result', 'onSuccess,onSync,onEffect,onMorph,onFinish,onRender,') + ; + } ++ ++ public function test_unsubscribing_an_interceptor_twice_does_not_remove_another_one() ++ { ++ Livewire::visit( ++ new class extends \Livewire\Component { ++ public function render() { ++ return <<<'HTML' ++
++ ++
++ @script ++ ++ @endscript ++ HTML; ++ } ++ } ++ ) ++ ->waitForLivewireToLoad() ++ ->waitForLivewire()->click('@refresh') ++ ->assertScript('window.intercepts', ['second']) ++ ; ++ } ++ ++ public function test_a_component_message_interceptor_can_be_unsubscribed() ++ { ++ Livewire::visit( ++ new class extends \Livewire\Component { ++ public function render() { ++ return <<<'HTML' ++
++ ++
++ @script ++ ++ @endscript ++ HTML; ++ } ++ } ++ ) ++ ->waitForLivewireToLoad() ++ ->waitForLivewire()->click('@refresh') ++ ->assertScript('window.intercepts', ['second']) ++ ; ++ } + } diff --git a/tasks/livewire__livewire-10758/solution/solve.sh b/tasks/livewire__livewire-10758/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/livewire__livewire-10758/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/livewire__livewire-10758/task.toml b/tasks/livewire__livewire-10758/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..3bdad535bf4edcd26492febef96153582aa24922 --- /dev/null +++ b/tasks/livewire__livewire-10758/task.toml @@ -0,0 +1,72 @@ +version = "1.0" + +[task] +name = "trending/livewire__livewire-10758" +description = "[4.x] Fix interceptor unsubscribe functions removing the wrong interceptor or throwing" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "livewire", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "livewire/livewire" +ref = "d0b4e22841d362dd213ee9602c399594d387b6ee" +reference = "https://github.com/livewire/livewire/pull/10758" +source_access = "auto" +built_at = "2026-11-16T16:09:51.437904+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:aee57b2ef95104a9bbc60f7ecfc5518ce6d6fac1b3adb49a0d858c2ca12ac5ce" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-10-07T11:41:29Z" +diff_format = "unified" +context_files = [ + "js/component.js", + "js/request/index.js", + "js/request/interceptor.js", + "js/utils.js", + "src/Features/SupportInterceptors/BrowserTest.php", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 89 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.429693+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:108fd5bbaa619e83c7b309cc26c21beaddb12766fe0d939f64edd86f874f671a" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/livewire__livewire-10758/tests/capture.py b/tasks/livewire__livewire-10758/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/livewire__livewire-10758/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/livewire__livewire-10758/tests/instruction.md b/tasks/livewire__livewire-10758/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..06e04993614c12800437bb4737d66cb3bf168114 --- /dev/null +++ b/tasks/livewire__livewire-10758/tests/instruction.md @@ -0,0 +1,28 @@ +# Issue + +**Title:** [4.x] Fix interceptor unsubscribe functions removing the wrong interceptor or throwing + +## Description + +Interceptor unsubscribe functions remove their callback with `splice(indexOf(callback), 1)`. If the callback is already gone, `indexOf()` returns `-1` and `splice(-1, 1)` removes whichever interceptor was registered last: + +```js +let unsubscribe = $wire.intercept(() => { /* first */ }) + +$wire.intercept(() => { /* second */ }) + +unsubscribe() +unsubscribe() // Removes "second"... +``` + +Separately, the unsubscribe returned by `$wire.interceptMessage()` calls `WeakBag::delete()`, which doesn't exist, so it throws and never removes anything. + +This PR adds a tiny `arrayPull(array, item)` helper that only splices when the item is present, and uses it in every interceptor unsubscribe (and in `Component::addCleanup()`, which already did this check by hand). Component message interceptors now pull their own callback from the component's list. + +Two browser tests cover both cases and fail without the fix. + +Pairs with #10759 (same area, no conflicts between them). + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d0b4e22841d3`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10758/tests/oracle.patch b/tasks/livewire__livewire-10758/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..8cf58a8bd887913766bdf83fe16795ff7f3677cd --- /dev/null +++ b/tasks/livewire__livewire-10758/tests/oracle.patch @@ -0,0 +1,175 @@ +diff --git a/js/component.js b/js/component.js +index 804733a7..57f422c9 100644 +--- a/js/component.js ++++ b/js/component.js +@@ -1,4 +1,4 @@ +-import { dataSet, deepClone, diff, diffAndConsolidate, diffAndPatchRecursive, extractData} from '@/utils' ++import { arrayPull, dataSet, deepClone, diff, diffAndConsolidate, diffAndPatchRecursive, extractData} from '@/utils' + import { generateWireObject } from '@/$wire' + import { findComponentByEl, findComponent, hasComponent } from '@/store' + import { trigger } from '@/hooks' +@@ -324,11 +324,7 @@ export class Component { + this.cleanups.push(cleanup) + + return () => { +- let index = this.cleanups.indexOf(cleanup) +- +- if (index === -1) return +- +- this.cleanups.splice(index, 1) ++ arrayPull(this.cleanups, cleanup) + } + } + +diff --git a/js/request/index.js b/js/request/index.js +index 26279906..0e22415d 100644 +--- a/js/request/index.js ++++ b/js/request/index.js +@@ -1,4 +1,4 @@ +-import { getCsrfToken, contentIsFromDump, splitDumpFromContent, getUpdateUri } from '@/utils' ++import { arrayPull, getCsrfToken, contentIsFromDump, splitDumpFromContent, getUpdateUri } from '@/utils' + import { coordinateNetworkInteractions } from './interactions.js' + import { MessageRequest, PageRequest } from './request.js' + import { InterceptorRegistry } from './interceptor.js' +@@ -37,7 +37,7 @@ export function interceptAction(callback) { + actionInterceptors.push(callback) + + return () => { +- actionInterceptors.splice(actionInterceptors.indexOf(callback), 1) ++ arrayPull(actionInterceptors, callback) + } + } + +@@ -53,7 +53,7 @@ export function interceptPartition(callback) { + partitionInterceptors.push(callback) + + return () => { +- partitionInterceptors.splice(partitionInterceptors.indexOf(callback), 1) ++ arrayPull(partitionInterceptors, callback) + } + } + +diff --git a/js/request/interceptor.js b/js/request/interceptor.js +index df2df69b..10534393 100644 +--- a/js/request/interceptor.js ++++ b/js/request/interceptor.js +@@ -1,4 +1,4 @@ +-import { WeakBag } from "@/utils" ++import { arrayPull, WeakBag } from "@/utils" + + export class MessageInterceptor { + onSend = () => {} +@@ -95,7 +95,7 @@ export class InterceptorRegistry { + this.messageInterceptorCallbacksByComponent.add(component, callback) + + return () => { +- this.messageInterceptorCallbacksByComponent.delete(component, callback) ++ arrayPull(this.messageInterceptorCallbacksByComponent.get(component), callback) + } + } + +@@ -103,7 +103,7 @@ export class InterceptorRegistry { + this.messageInterceptorCallbacks.push(callback) + + return () => { +- this.messageInterceptorCallbacks.splice(this.messageInterceptorCallbacks.indexOf(callback), 1) ++ arrayPull(this.messageInterceptorCallbacks, callback) + } + } + +@@ -111,7 +111,7 @@ export class InterceptorRegistry { + this.requestInterceptorCallbacks.push(callback) + + return () => { +- this.requestInterceptorCallbacks.splice(this.requestInterceptorCallbacks.indexOf(callback), 1) ++ arrayPull(this.requestInterceptorCallbacks, callback) + } + } + +diff --git a/js/utils.js b/js/utils.js +index 0a85f6aa..60ba65cd 100644 +--- a/js/utils.js ++++ b/js/utils.js +@@ -33,6 +33,12 @@ export class WeakBag { + each(key, callback) { return this.get(key).forEach(callback) } + } + ++export function arrayPull(array, item) { ++ let index = array.indexOf(item) ++ ++ if (index !== -1) array.splice(index, 1) ++} ++ + export function dispatch(target, name, detail = {}, bubbles = true) { + target.dispatchEvent( + new CustomEvent(name, { +diff --git a/src/Features/SupportInterceptors/BrowserTest.php b/src/Features/SupportInterceptors/BrowserTest.php +index c32f7145..00fdf3f2 100644 +--- a/src/Features/SupportInterceptors/BrowserTest.php ++++ b/src/Features/SupportInterceptors/BrowserTest.php +@@ -706,4 +706,65 @@ class BrowserTest extends \Tests\BrowserTestCase + ->assertSeeIn('@result', 'onSuccess,onSync,onEffect,onMorph,onFinish,onRender,') + ; + } ++ ++ public function test_unsubscribing_an_interceptor_twice_does_not_remove_another_one() ++ { ++ Livewire::visit( ++ new class extends \Livewire\Component { ++ public function render() { ++ return <<<'HTML' ++
++ ++
++ @script ++ ++ @endscript ++ HTML; ++ } ++ } ++ ) ++ ->waitForLivewireToLoad() ++ ->waitForLivewire()->click('@refresh') ++ ->assertScript('window.intercepts', ['second']) ++ ; ++ } ++ ++ public function test_a_component_message_interceptor_can_be_unsubscribed() ++ { ++ Livewire::visit( ++ new class extends \Livewire\Component { ++ public function render() { ++ return <<<'HTML' ++
++ ++
++ @script ++ ++ @endscript ++ HTML; ++ } ++ } ++ ) ++ ->waitForLivewireToLoad() ++ ->waitForLivewire()->click('@refresh') ++ ->assertScript('window.intercepts', ['second']) ++ ; ++ } + } diff --git a/tasks/livewire__livewire-10758/tests/test.sh b/tasks/livewire__livewire-10758/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..f4255995d98bc2c91067af5b4e4a6a330f30ec75 --- /dev/null +++ b/tasks/livewire__livewire-10758/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace d0b4e22841d362dd213ee9602c399594d387b6ee > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/livewire__livewire-10758/tests/verifier.py b/tasks/livewire__livewire-10758/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/livewire__livewire-10758/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/livewire__livewire-10759/environment/Dockerfile b/tasks/livewire__livewire-10759/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2b0e159ee8ce195ce98a086105e83d9d0bd84fd4 --- /dev/null +++ b/tasks/livewire__livewire-10759/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/livewire/livewire.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/livewire/livewire.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/livewire/livewire.git +WORKDIR /workspace +RUN git fetch --depth 1 origin d0b4e22841d362dd213ee9602c399594d387b6ee 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard d0b4e22841d362dd213ee9602c399594d387b6ee \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base d0b4e22841d362dd213ee9602c399594d387b6ee \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/livewire__livewire-10759/instruction.md b/tasks/livewire__livewire-10759/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..15abfb092653ddf6c572753dce0737259cbcad69 --- /dev/null +++ b/tasks/livewire__livewire-10759/instruction.md @@ -0,0 +1,29 @@ +# Issue + +**Title:** [4.x] Fix an interceptor unsubscribing itself skipping the next one + +## Description + +Action and request interceptors run in a `forEach` over the registry's own array. If one unsubscribes during that loop, the array shifts and the next interceptor is skipped for that action: + +```js +let unsubscribe = $wire.intercept(() => { + unsubscribe() // Only run once... +}) + +$wire.intercept(() => { + // Skipped on the first action... +}) +``` + +This PR iterates over a copy of the array in `fireAction()`, `sendMessages()` (partition interceptors) and `getRequestInterceptors()`. `getMessageInterceptors()` already builds a new array. + +One small behavior change: an interceptor removed by *another* interceptor mid-loop still runs for that one action, the same way Alpine's `$watch` behaves. + +A browser test covers action and request interceptors and fails without the fix. + +Pairs with #10758 (same area, no conflicts between them). + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d0b4e22841d3`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10759/solution/patch.diff b/tasks/livewire__livewire-10759/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..e616fcb8f1bb56564c8f5e37633164d4d067d77a --- /dev/null +++ b/tasks/livewire__livewire-10759/solution/patch.diff @@ -0,0 +1,92 @@ +diff --git a/js/request/index.js b/js/request/index.js +index 26279906..6c3080c9 100644 +--- a/js/request/index.js ++++ b/js/request/index.js +@@ -123,7 +123,7 @@ export function fireAction(component, method, params = [], metadata = {}) { + + let action = constructAction(component, method, params, metadata) + +- actionInterceptors.forEach(callback => { ++ Array.from(actionInterceptors).forEach(callback => { + callback({ + action, + onSend: (cb) => action.onSendCallbacks.push(cb), +@@ -191,7 +191,7 @@ function sendMessages() { + let requests = new Set() + + messageBus.eachPendingMessage(message => { +- partitionInterceptors.forEach(callback => { ++ Array.from(partitionInterceptors).forEach(callback => { + callback({ + message, + compileRequest: (messages) => { +diff --git a/js/request/interceptor.js b/js/request/interceptor.js +index df2df69b..58538f05 100644 +--- a/js/request/interceptor.js ++++ b/js/request/interceptor.js +@@ -127,7 +127,7 @@ export class InterceptorRegistry { + } + + getRequestInterceptors(request) { +- return this.requestInterceptorCallbacks.map(callback => { ++ return Array.from(this.requestInterceptorCallbacks).map(callback => { + return new RequestInterceptor(request, callback) + }) + } +diff --git a/src/Features/SupportInterceptors/BrowserTest.php b/src/Features/SupportInterceptors/BrowserTest.php +index c32f7145..607eaeb9 100644 +--- a/src/Features/SupportInterceptors/BrowserTest.php ++++ b/src/Features/SupportInterceptors/BrowserTest.php +@@ -135,6 +135,52 @@ class BrowserTest extends \Tests\BrowserTestCase + ; + } + ++ public function test_action_and_request_interceptors_unsubscribing_do_not_skip_the_next_one() ++ { ++ Livewire::visit( ++ new class extends \Livewire\Component { ++ public function render() { ++ return <<<'HTML' ++
++ ++
++ @script ++ ++ @endscript ++ HTML; ++ } ++ } ++ ) ++ ->waitForLivewireToLoad() ++ ->waitForLivewire()->click('@refresh') ++ ->assertScript('window.intercepts', ['action once', 'action', 'request once', 'request']) ++ ++ // Reset... ++ ->tap(fn ($browser) => $browser->script('window.intercepts = []')) ++ ++ ->waitForLivewire()->click('@refresh') ++ ->assertScript('window.intercepts', ['action', 'request']) ++ ; ++ } ++ + public function test_an_interceptor_can_have_multiple_callbacks() + { + Livewire::visit([ diff --git a/tasks/livewire__livewire-10759/solution/solve.sh b/tasks/livewire__livewire-10759/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/livewire__livewire-10759/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/livewire__livewire-10759/task.toml b/tasks/livewire__livewire-10759/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..aa4d5d90d633302eb8a175245bee13e804f9e6a3 --- /dev/null +++ b/tasks/livewire__livewire-10759/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/livewire__livewire-10759" +description = "[4.x] Fix an interceptor unsubscribing itself skipping the next one" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "livewire", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "livewire/livewire" +ref = "d0b4e22841d362dd213ee9602c399594d387b6ee" +reference = "https://github.com/livewire/livewire/pull/10759" +source_access = "auto" +built_at = "2026-11-16T16:09:51.440067+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:2462a09f4277c56961b4febeeacd2a53beb6d385e27d7414bc2cdfdbc3c17826" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-10-07T11:41:06Z" +diff_format = "unified" +context_files = [ + "js/request/index.js", + "js/request/interceptor.js", + "src/Features/SupportInterceptors/BrowserTest.php", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 52 +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.430192+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:108fd5bbaa619e83c7b309cc26c21beaddb12766fe0d939f64edd86f874f671a" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/livewire__livewire-10759/tests/capture.py b/tasks/livewire__livewire-10759/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/livewire__livewire-10759/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/livewire__livewire-10759/tests/instruction.md b/tasks/livewire__livewire-10759/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..15abfb092653ddf6c572753dce0737259cbcad69 --- /dev/null +++ b/tasks/livewire__livewire-10759/tests/instruction.md @@ -0,0 +1,29 @@ +# Issue + +**Title:** [4.x] Fix an interceptor unsubscribing itself skipping the next one + +## Description + +Action and request interceptors run in a `forEach` over the registry's own array. If one unsubscribes during that loop, the array shifts and the next interceptor is skipped for that action: + +```js +let unsubscribe = $wire.intercept(() => { + unsubscribe() // Only run once... +}) + +$wire.intercept(() => { + // Skipped on the first action... +}) +``` + +This PR iterates over a copy of the array in `fireAction()`, `sendMessages()` (partition interceptors) and `getRequestInterceptors()`. `getMessageInterceptors()` already builds a new array. + +One small behavior change: an interceptor removed by *another* interceptor mid-loop still runs for that one action, the same way Alpine's `$watch` behaves. + +A browser test covers action and request interceptors and fails without the fix. + +Pairs with #10758 (same area, no conflicts between them). + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d0b4e22841d3`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10759/tests/oracle.patch b/tasks/livewire__livewire-10759/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..e616fcb8f1bb56564c8f5e37633164d4d067d77a --- /dev/null +++ b/tasks/livewire__livewire-10759/tests/oracle.patch @@ -0,0 +1,92 @@ +diff --git a/js/request/index.js b/js/request/index.js +index 26279906..6c3080c9 100644 +--- a/js/request/index.js ++++ b/js/request/index.js +@@ -123,7 +123,7 @@ export function fireAction(component, method, params = [], metadata = {}) { + + let action = constructAction(component, method, params, metadata) + +- actionInterceptors.forEach(callback => { ++ Array.from(actionInterceptors).forEach(callback => { + callback({ + action, + onSend: (cb) => action.onSendCallbacks.push(cb), +@@ -191,7 +191,7 @@ function sendMessages() { + let requests = new Set() + + messageBus.eachPendingMessage(message => { +- partitionInterceptors.forEach(callback => { ++ Array.from(partitionInterceptors).forEach(callback => { + callback({ + message, + compileRequest: (messages) => { +diff --git a/js/request/interceptor.js b/js/request/interceptor.js +index df2df69b..58538f05 100644 +--- a/js/request/interceptor.js ++++ b/js/request/interceptor.js +@@ -127,7 +127,7 @@ export class InterceptorRegistry { + } + + getRequestInterceptors(request) { +- return this.requestInterceptorCallbacks.map(callback => { ++ return Array.from(this.requestInterceptorCallbacks).map(callback => { + return new RequestInterceptor(request, callback) + }) + } +diff --git a/src/Features/SupportInterceptors/BrowserTest.php b/src/Features/SupportInterceptors/BrowserTest.php +index c32f7145..607eaeb9 100644 +--- a/src/Features/SupportInterceptors/BrowserTest.php ++++ b/src/Features/SupportInterceptors/BrowserTest.php +@@ -135,6 +135,52 @@ class BrowserTest extends \Tests\BrowserTestCase + ; + } + ++ public function test_action_and_request_interceptors_unsubscribing_do_not_skip_the_next_one() ++ { ++ Livewire::visit( ++ new class extends \Livewire\Component { ++ public function render() { ++ return <<<'HTML' ++
++ ++
++ @script ++ ++ @endscript ++ HTML; ++ } ++ } ++ ) ++ ->waitForLivewireToLoad() ++ ->waitForLivewire()->click('@refresh') ++ ->assertScript('window.intercepts', ['action once', 'action', 'request once', 'request']) ++ ++ // Reset... ++ ->tap(fn ($browser) => $browser->script('window.intercepts = []')) ++ ++ ->waitForLivewire()->click('@refresh') ++ ->assertScript('window.intercepts', ['action', 'request']) ++ ; ++ } ++ + public function test_an_interceptor_can_have_multiple_callbacks() + { + Livewire::visit([ diff --git a/tasks/livewire__livewire-10759/tests/test.sh b/tasks/livewire__livewire-10759/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..f4255995d98bc2c91067af5b4e4a6a330f30ec75 --- /dev/null +++ b/tasks/livewire__livewire-10759/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace d0b4e22841d362dd213ee9602c399594d387b6ee > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/livewire__livewire-10759/tests/verifier.py b/tasks/livewire__livewire-10759/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/livewire__livewire-10759/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/livewire__livewire-10762/environment/Dockerfile b/tasks/livewire__livewire-10762/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..05da7619a4c1b9cd5ace748e4a9eb39d737fd5bb --- /dev/null +++ b/tasks/livewire__livewire-10762/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/livewire/livewire.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/livewire/livewire.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/livewire/livewire.git +WORKDIR /workspace +RUN git fetch --depth 1 origin ada5a07830c7a6a5bce2272ceea38259482d04a0 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard ada5a07830c7a6a5bce2272ceea38259482d04a0 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base ada5a07830c7a6a5bce2272ceea38259482d04a0 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/livewire__livewire-10762/instruction.md b/tasks/livewire__livewire-10762/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0bb1e678475f87c5929292bdf2f8ff53bd53d73b --- /dev/null +++ b/tasks/livewire__livewire-10762/instruction.md @@ -0,0 +1,15 @@ +# Issue + +**Title:** [4.x] Fix MIME detection for MP3 uploads with ID3 tags larger than 64 KiB + +## Description + +Since 4.4.2, `TemporaryUploadedFile::getMimeType()` detects the type from the first 64 KiB of the upload. A lot of MP3s start with an ID3v2 tag that holds the cover art, and that tag is often bigger than 64 KiB. When it is, the sample has no audio data in it, finfo returns `application/octet-stream`, and `mimes:mp3` fails on a valid file. `temporaryUrl()` breaks too, because `isPreviewable()` goes through the same MIME type. + +The ID3 header stores the tag size in bytes 6-9. If the sample starts with `ID3`, this reads that many more bytes from the same stream (capped at 8 MiB), so the buffer holds the whole tag plus the start of the audio. Other files still get the 64 KiB sample, and it's still one `readStream()` call. + +I added a test that puts a 70 KiB ID3 tag in front of some MPEG frames on the S3-like test disk. Before the fix it reports `application/octet-stream`. After the fix it reports `audio/mpeg`. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `ada5a07830c7`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10762/solution/patch.diff b/tasks/livewire__livewire-10762/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..d7efb0b4b13c1bc2e219f46808a7d3d6bf0931c0 --- /dev/null +++ b/tasks/livewire__livewire-10762/solution/patch.diff @@ -0,0 +1,49 @@ +diff --git a/src/Features/SupportFileUploads/TemporaryUploadedFile.php b/src/Features/SupportFileUploads/TemporaryUploadedFile.php +index f5902e37..5b5b0c76 100644 +--- a/src/Features/SupportFileUploads/TemporaryUploadedFile.php ++++ b/src/Features/SupportFileUploads/TemporaryUploadedFile.php +@@ -92,6 +92,16 @@ class TemporaryUploadedFile extends UploadedFile + try { + // Avoid downloading the entire object when the temporary disk is remote... + $contents = stream_get_contents($stream, 64 * 1024); ++ ++ // MP3s can start with an ID3 tag (e.g. cover art) bigger than the sample, so read past it... ++ if (is_string($contents) && strlen($contents) >= 10 && str_starts_with($contents, 'ID3')) { ++ $tagSize = (ord($contents[6]) & 0x7F) << 21 ++ | (ord($contents[7]) & 0x7F) << 14 ++ | (ord($contents[8]) & 0x7F) << 7 ++ | (ord($contents[9]) & 0x7F); ++ ++ $contents .= stream_get_contents($stream, min($tagSize, 8 * 1024 * 1024)); ++ } + } finally { + fclose($stream); + } +diff --git a/src/Features/SupportFileUploads/UnitTest.php b/src/Features/SupportFileUploads/UnitTest.php +index 765170cc..c58f18fb 100644 +--- a/src/Features/SupportFileUploads/UnitTest.php ++++ b/src/Features/SupportFileUploads/UnitTest.php +@@ -917,6 +917,23 @@ class UnitTest extends \Tests\TestCase + $this->assertSame(1, $disk->readStreamCalls); + } + ++ public function test_temporary_upload_mime_type_is_detected_past_an_id3_tag_larger_than_the_sample() ++ { ++ $disk = $this->useS3LikeTemporaryUploadDisk(); ++ ++ // A 70 KiB ID3v2 tag (like one holding cover art) followed by MPEG audio frames... ++ $tag = "ID3\x03\x00\x00\x00\x04\x30\x00".str_repeat("\x00", 70 * 1024); ++ $frames = str_repeat("\xFF\xFB\x90\x64".str_repeat("\x00", 413), 10); ++ ++ $disk->put('livewire-tmp/song.mp3', $tag.$frames); ++ ++ $file = TemporaryUploadedFile::createFromLivewire('song.mp3'); ++ ++ $this->assertSame('audio/mpeg', $file->getMimeType()); ++ $this->assertTrue(validator(['file' => $file], ['file' => 'mimes:mp3'])->passes()); ++ $this->assertSame(1, $disk->readStreamCalls); ++ } ++ + public function test_temporary_upload_mime_type_does_not_fall_back_to_storage_metadata_for_empty_files() + { + $disk = $this->useS3LikeTemporaryUploadDisk(); diff --git a/tasks/livewire__livewire-10762/solution/solve.sh b/tasks/livewire__livewire-10762/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/livewire__livewire-10762/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/livewire__livewire-10762/task.toml b/tasks/livewire__livewire-10762/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..12c07d9d2559d2d405048339cb8319f0b511156f --- /dev/null +++ b/tasks/livewire__livewire-10762/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/livewire__livewire-10762" +description = "[4.x] Fix MIME detection for MP3 uploads with ID3 tags larger than 64 KiB" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "livewire", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "livewire/livewire" +ref = "ada5a07830c7a6a5bce2272ceea38259482d04a0" +reference = "https://github.com/livewire/livewire/pull/10762" +source_access = "auto" +built_at = "2026-11-16T16:09:51.416155+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:924bc07cdfb52108aba7ad24c805c8f0826e43d627e5b5b34cdd216c3f1238ec" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-10-07T12:27:48Z" +diff_format = "unified" +context_files = [ + "src/Features/SupportFileUploads/TemporaryUploadedFile.php", + "src/Features/SupportFileUploads/UnitTest.php", +] +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.430722+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:a91ba79859437a95bf2efd6b6721dda335fd6f0943787de03cd1bc1f178e31c3" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/livewire__livewire-10762/tests/capture.py b/tasks/livewire__livewire-10762/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/livewire__livewire-10762/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/livewire__livewire-10762/tests/instruction.md b/tasks/livewire__livewire-10762/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0bb1e678475f87c5929292bdf2f8ff53bd53d73b --- /dev/null +++ b/tasks/livewire__livewire-10762/tests/instruction.md @@ -0,0 +1,15 @@ +# Issue + +**Title:** [4.x] Fix MIME detection for MP3 uploads with ID3 tags larger than 64 KiB + +## Description + +Since 4.4.2, `TemporaryUploadedFile::getMimeType()` detects the type from the first 64 KiB of the upload. A lot of MP3s start with an ID3v2 tag that holds the cover art, and that tag is often bigger than 64 KiB. When it is, the sample has no audio data in it, finfo returns `application/octet-stream`, and `mimes:mp3` fails on a valid file. `temporaryUrl()` breaks too, because `isPreviewable()` goes through the same MIME type. + +The ID3 header stores the tag size in bytes 6-9. If the sample starts with `ID3`, this reads that many more bytes from the same stream (capped at 8 MiB), so the buffer holds the whole tag plus the start of the audio. Other files still get the 64 KiB sample, and it's still one `readStream()` call. + +I added a test that puts a 70 KiB ID3 tag in front of some MPEG frames on the S3-like test disk. Before the fix it reports `application/octet-stream`. After the fix it reports `audio/mpeg`. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `ada5a07830c7`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10762/tests/oracle.patch b/tasks/livewire__livewire-10762/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..d7efb0b4b13c1bc2e219f46808a7d3d6bf0931c0 --- /dev/null +++ b/tasks/livewire__livewire-10762/tests/oracle.patch @@ -0,0 +1,49 @@ +diff --git a/src/Features/SupportFileUploads/TemporaryUploadedFile.php b/src/Features/SupportFileUploads/TemporaryUploadedFile.php +index f5902e37..5b5b0c76 100644 +--- a/src/Features/SupportFileUploads/TemporaryUploadedFile.php ++++ b/src/Features/SupportFileUploads/TemporaryUploadedFile.php +@@ -92,6 +92,16 @@ class TemporaryUploadedFile extends UploadedFile + try { + // Avoid downloading the entire object when the temporary disk is remote... + $contents = stream_get_contents($stream, 64 * 1024); ++ ++ // MP3s can start with an ID3 tag (e.g. cover art) bigger than the sample, so read past it... ++ if (is_string($contents) && strlen($contents) >= 10 && str_starts_with($contents, 'ID3')) { ++ $tagSize = (ord($contents[6]) & 0x7F) << 21 ++ | (ord($contents[7]) & 0x7F) << 14 ++ | (ord($contents[8]) & 0x7F) << 7 ++ | (ord($contents[9]) & 0x7F); ++ ++ $contents .= stream_get_contents($stream, min($tagSize, 8 * 1024 * 1024)); ++ } + } finally { + fclose($stream); + } +diff --git a/src/Features/SupportFileUploads/UnitTest.php b/src/Features/SupportFileUploads/UnitTest.php +index 765170cc..c58f18fb 100644 +--- a/src/Features/SupportFileUploads/UnitTest.php ++++ b/src/Features/SupportFileUploads/UnitTest.php +@@ -917,6 +917,23 @@ class UnitTest extends \Tests\TestCase + $this->assertSame(1, $disk->readStreamCalls); + } + ++ public function test_temporary_upload_mime_type_is_detected_past_an_id3_tag_larger_than_the_sample() ++ { ++ $disk = $this->useS3LikeTemporaryUploadDisk(); ++ ++ // A 70 KiB ID3v2 tag (like one holding cover art) followed by MPEG audio frames... ++ $tag = "ID3\x03\x00\x00\x00\x04\x30\x00".str_repeat("\x00", 70 * 1024); ++ $frames = str_repeat("\xFF\xFB\x90\x64".str_repeat("\x00", 413), 10); ++ ++ $disk->put('livewire-tmp/song.mp3', $tag.$frames); ++ ++ $file = TemporaryUploadedFile::createFromLivewire('song.mp3'); ++ ++ $this->assertSame('audio/mpeg', $file->getMimeType()); ++ $this->assertTrue(validator(['file' => $file], ['file' => 'mimes:mp3'])->passes()); ++ $this->assertSame(1, $disk->readStreamCalls); ++ } ++ + public function test_temporary_upload_mime_type_does_not_fall_back_to_storage_metadata_for_empty_files() + { + $disk = $this->useS3LikeTemporaryUploadDisk(); diff --git a/tasks/livewire__livewire-10762/tests/test.sh b/tasks/livewire__livewire-10762/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..4480f9890d6d694c073d5719e658f54374a9ce8a --- /dev/null +++ b/tasks/livewire__livewire-10762/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace ada5a07830c7a6a5bce2272ceea38259482d04a0 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/livewire__livewire-10762/tests/verifier.py b/tasks/livewire__livewire-10762/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/livewire__livewire-10762/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/livewire__livewire-10765/environment/Dockerfile b/tasks/livewire__livewire-10765/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..99fe69a2970fbe383558a99d4ad5eb1898df8735 --- /dev/null +++ b/tasks/livewire__livewire-10765/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/livewire/livewire.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/livewire/livewire.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/livewire/livewire.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 5f97f2175a270a55db9140db401d5e39d34d67c0 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 5f97f2175a270a55db9140db401d5e39d34d67c0 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 5f97f2175a270a55db9140db401d5e39d34d67c0 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/livewire__livewire-10765/instruction.md b/tasks/livewire__livewire-10765/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..11edf4d38cdad1d4307e83b43cf1547b853cb062 --- /dev/null +++ b/tasks/livewire__livewire-10765/instruction.md @@ -0,0 +1,20 @@ +# Issue + +**Title:** [3.x] Stabilize loading delay browser test + +## Description + +Backports the test-only timing stabilization from #10725 to 3.x. + +The exact-head 3.x matrix failed the same `test_different_delay_durations` test twice on the Laravel 12 / PHP 8.5 shard, with different threshold selectors failing across attempts. Production loading code is unchanged. The stabilized test uses wider browser-observable windows and keeps the request alive long enough to cover the 1000ms `longest` modifier. + +Verification: +- cherry-picked the exact #10725 stabilization commit onto current 3.x +- focused LegacyBrowser test passed 3 consecutive local runs +- 1 test / 16 assertions per run +- `npm run build` passed +- `git diff --check` passed + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `5f97f2175a27`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10765/solution/patch.diff b/tasks/livewire__livewire-10765/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..e98b5887b9aeeac1be3e4e1c0a4fc3858101b0fd --- /dev/null +++ b/tasks/livewire__livewire-10765/solution/patch.diff @@ -0,0 +1,86 @@ +diff --git a/legacy_tests/Browser/Loading/ComponentWithLoadingDelays.php b/legacy_tests/Browser/Loading/ComponentWithLoadingDelays.php +index f39f7b3c..23b1b9bd 100644 +--- a/legacy_tests/Browser/Loading/ComponentWithLoadingDelays.php ++++ b/legacy_tests/Browser/Loading/ComponentWithLoadingDelays.php +@@ -10,8 +10,8 @@ class ComponentWithLoadingDelays extends BaseComponent + + public function hydrate() + { +- // Sleep for up to 1100ms as longest is 1000ms +- usleep(1000 * 1100); ++ // Sleep long enough to observe the 1000ms longest delay with room for browser scheduling. ++ usleep(1000 * 1500); + } + + public function render() +diff --git a/legacy_tests/Browser/Loading/Test.php b/legacy_tests/Browser/Loading/Test.php +index c06172b3..2bb4726c 100644 +--- a/legacy_tests/Browser/Loading/Test.php ++++ b/legacy_tests/Browser/Loading/Test.php +@@ -159,47 +159,34 @@ class Test extends TestCase + ->assertNotVisible('@delay-shortest') + ->waitForLivewire(function (Browser $browser) { + $browser->click('@load') +- ->assertNotVisible('@delay-shortest') +- ->assertVisible('@delay-none'); ++ ->waitFor('@delay-none'); + })->waitForLivewire(function (Browser $browser) { + $browser->click('@load') +- ->pause(51) +- ->assertNotVisible('@delay-shorter') +- ->assertVisible('@delay-shortest'); ++ ->pause(250) ++ ->assertNotVisible('@delay-long') ++ ->assertNotVisible('@delay-longer') ++ ->assertNotVisible('@delay-longest') ++ ->assertVisible('@delay-shortest') ++ ->assertVisible('@delay-shorter') ++ ->assertVisible('@delay-short') ++ ->assertVisible('@delay') ++ ->assertVisible('@delay-default'); + })->waitForLivewire(function (Browser $browser) { + $browser->click('@load') +- ->pause(101) +- ->assertNotVisible('@delay-short') +- ->assertVisible('@delay-shorter'); ++ ->pause(400) ++ ->assertNotVisible('@delay-longer') ++ ->assertNotVisible('@delay-longest') ++ ->assertVisible('@delay-long'); + })->waitForLivewire(function (Browser $browser) { + $browser->click('@load') +- ->pause(151) +- ->assertNotVisible('@delay') +- ->assertNotVisible('@delay-default') +- ->assertVisible('@delay-short'); ++ ->pause(750) ++ ->assertNotVisible('@delay-longest') ++ ->assertVisible('@delay-longer'); + })->waitForLivewire(function (Browser $browser) { + $browser->click('@load') +- ->pause(201) +- ->assertNotVisible('@delay-long') +- ->assertVisible('@delay') +- ->assertVisible('@delay-default'); +- })->waitForLivewire(function (Browser $browser) { +- $browser->click('@load') +- ->pause(301) +- ->assertNotVisible('@delay-longer') +- ->assertVisible('@delay-long'); +- })->waitForLivewire(function (Browser $browser) { +- $browser->click('@load') +- ->pause(501) +- ->assertNotVisible('@delay-longest') +- ->assertVisible('@delay-longer'); ++ ->pause(1250) ++ ->assertVisible('@delay-longest'); + }); +- // @todo: this is flaky... +- // })->waitForLivewire(function (Browser $browser) { +- // $browser->click('@load') +- // ->pause(1002) +- // ->assertVisible('@delay-longest'); +- // }); + }); + } + diff --git a/tasks/livewire__livewire-10765/solution/solve.sh b/tasks/livewire__livewire-10765/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/livewire__livewire-10765/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/livewire__livewire-10765/task.toml b/tasks/livewire__livewire-10765/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..81dc7d17619b9368a6a4cd13a3cd8b4da72d6184 --- /dev/null +++ b/tasks/livewire__livewire-10765/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/livewire__livewire-10765" +description = "[3.x] Stabilize loading delay browser test" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "livewire", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "livewire/livewire" +ref = "5f97f2175a270a55db9140db401d5e39d34d67c0" +reference = "https://github.com/livewire/livewire/pull/10765" +source_access = "auto" +built_at = "2026-11-16T16:09:51.452058+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:91f23fc9275c92e64acc1dcb4dd771ebd51e4376d6bb86d2e907b6c1c06661fe" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-28T16:49:24Z" +diff_format = "unified" +context_files = [ + "legacy_tests/Browser/Loading/ComponentWithLoadingDelays.php", + "legacy_tests/Browser/Loading/Test.php", +] +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.431253+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:84908068487233367c1f99fb6f9df6b74576cce1d94c4177b0cdc821468dc673" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/livewire__livewire-10765/tests/capture.py b/tasks/livewire__livewire-10765/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/livewire__livewire-10765/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/livewire__livewire-10765/tests/instruction.md b/tasks/livewire__livewire-10765/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..11edf4d38cdad1d4307e83b43cf1547b853cb062 --- /dev/null +++ b/tasks/livewire__livewire-10765/tests/instruction.md @@ -0,0 +1,20 @@ +# Issue + +**Title:** [3.x] Stabilize loading delay browser test + +## Description + +Backports the test-only timing stabilization from #10725 to 3.x. + +The exact-head 3.x matrix failed the same `test_different_delay_durations` test twice on the Laravel 12 / PHP 8.5 shard, with different threshold selectors failing across attempts. Production loading code is unchanged. The stabilized test uses wider browser-observable windows and keeps the request alive long enough to cover the 1000ms `longest` modifier. + +Verification: +- cherry-picked the exact #10725 stabilization commit onto current 3.x +- focused LegacyBrowser test passed 3 consecutive local runs +- 1 test / 16 assertions per run +- `npm run build` passed +- `git diff --check` passed + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `5f97f2175a27`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10765/tests/oracle.patch b/tasks/livewire__livewire-10765/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..e98b5887b9aeeac1be3e4e1c0a4fc3858101b0fd --- /dev/null +++ b/tasks/livewire__livewire-10765/tests/oracle.patch @@ -0,0 +1,86 @@ +diff --git a/legacy_tests/Browser/Loading/ComponentWithLoadingDelays.php b/legacy_tests/Browser/Loading/ComponentWithLoadingDelays.php +index f39f7b3c..23b1b9bd 100644 +--- a/legacy_tests/Browser/Loading/ComponentWithLoadingDelays.php ++++ b/legacy_tests/Browser/Loading/ComponentWithLoadingDelays.php +@@ -10,8 +10,8 @@ class ComponentWithLoadingDelays extends BaseComponent + + public function hydrate() + { +- // Sleep for up to 1100ms as longest is 1000ms +- usleep(1000 * 1100); ++ // Sleep long enough to observe the 1000ms longest delay with room for browser scheduling. ++ usleep(1000 * 1500); + } + + public function render() +diff --git a/legacy_tests/Browser/Loading/Test.php b/legacy_tests/Browser/Loading/Test.php +index c06172b3..2bb4726c 100644 +--- a/legacy_tests/Browser/Loading/Test.php ++++ b/legacy_tests/Browser/Loading/Test.php +@@ -159,47 +159,34 @@ class Test extends TestCase + ->assertNotVisible('@delay-shortest') + ->waitForLivewire(function (Browser $browser) { + $browser->click('@load') +- ->assertNotVisible('@delay-shortest') +- ->assertVisible('@delay-none'); ++ ->waitFor('@delay-none'); + })->waitForLivewire(function (Browser $browser) { + $browser->click('@load') +- ->pause(51) +- ->assertNotVisible('@delay-shorter') +- ->assertVisible('@delay-shortest'); ++ ->pause(250) ++ ->assertNotVisible('@delay-long') ++ ->assertNotVisible('@delay-longer') ++ ->assertNotVisible('@delay-longest') ++ ->assertVisible('@delay-shortest') ++ ->assertVisible('@delay-shorter') ++ ->assertVisible('@delay-short') ++ ->assertVisible('@delay') ++ ->assertVisible('@delay-default'); + })->waitForLivewire(function (Browser $browser) { + $browser->click('@load') +- ->pause(101) +- ->assertNotVisible('@delay-short') +- ->assertVisible('@delay-shorter'); ++ ->pause(400) ++ ->assertNotVisible('@delay-longer') ++ ->assertNotVisible('@delay-longest') ++ ->assertVisible('@delay-long'); + })->waitForLivewire(function (Browser $browser) { + $browser->click('@load') +- ->pause(151) +- ->assertNotVisible('@delay') +- ->assertNotVisible('@delay-default') +- ->assertVisible('@delay-short'); ++ ->pause(750) ++ ->assertNotVisible('@delay-longest') ++ ->assertVisible('@delay-longer'); + })->waitForLivewire(function (Browser $browser) { + $browser->click('@load') +- ->pause(201) +- ->assertNotVisible('@delay-long') +- ->assertVisible('@delay') +- ->assertVisible('@delay-default'); +- })->waitForLivewire(function (Browser $browser) { +- $browser->click('@load') +- ->pause(301) +- ->assertNotVisible('@delay-longer') +- ->assertVisible('@delay-long'); +- })->waitForLivewire(function (Browser $browser) { +- $browser->click('@load') +- ->pause(501) +- ->assertNotVisible('@delay-longest') +- ->assertVisible('@delay-longer'); ++ ->pause(1250) ++ ->assertVisible('@delay-longest'); + }); +- // @todo: this is flaky... +- // })->waitForLivewire(function (Browser $browser) { +- // $browser->click('@load') +- // ->pause(1002) +- // ->assertVisible('@delay-longest'); +- // }); + }); + } + diff --git a/tasks/livewire__livewire-10765/tests/test.sh b/tasks/livewire__livewire-10765/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..c0870a21c998e22bb2fbaf8de548ea5f448b17a3 --- /dev/null +++ b/tasks/livewire__livewire-10765/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 5f97f2175a270a55db9140db401d5e39d34d67c0 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/livewire__livewire-10765/tests/verifier.py b/tasks/livewire__livewire-10765/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/livewire__livewire-10765/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/livewire__livewire-10767/environment/Dockerfile b/tasks/livewire__livewire-10767/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..742b2decb1b39fa830bbd6953164617ae44eafb6 --- /dev/null +++ b/tasks/livewire__livewire-10767/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/livewire/livewire.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/livewire/livewire.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/livewire/livewire.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 3b2328babd06097f0f606c8fb98aeee3fc1c8610 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 3b2328babd06097f0f606c8fb98aeee3fc1c8610 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 3b2328babd06097f0f606c8fb98aeee3fc1c8610 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/livewire__livewire-10767/instruction.md b/tasks/livewire__livewire-10767/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6d9c9bc0492204276ca79ae90cf415686d598d4e --- /dev/null +++ b/tasks/livewire__livewire-10767/instruction.md @@ -0,0 +1,18 @@ +# Issue + +**Title:** Stabilize query string browser tests on 3.x + +## Description + +Backports the query-string browser test hardening already present on 4.x and main. + +- Wait for invalid nullable enum values to settle before asserting the URL +- Decode the browser query string before comparing bracketed keys + +This addresses the two deterministic failures exposed by Chrome 153 in the post-merge 3.x release gate. + +Verified locally with the four affected browser tests passing three consecutive runs (22 assertions each). + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `3b2328babd06`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10767/solution/patch.diff b/tasks/livewire__livewire-10767/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..5d00d6f0a4e1c5201e03c61ad44db3dee2f0da5c --- /dev/null +++ b/tasks/livewire__livewire-10767/solution/patch.diff @@ -0,0 +1,40 @@ +diff --git a/src/Features/SupportQueryString/BrowserTest.php b/src/Features/SupportQueryString/BrowserTest.php +index 59d786ec..dbb23de7 100644 +--- a/src/Features/SupportQueryString/BrowserTest.php ++++ b/src/Features/SupportQueryString/BrowserTest.php +@@ -513,7 +513,7 @@ class BrowserTest extends \Tests\BrowserTestCase + } + }, + ]) +- ->assertQueryStringHas('foo', '') ++ ->waitForQueryString('foo', '') + ->assertSee('foo', null) + ->waitForLivewire()->click('@button') + ->assertQueryStringHas('foo', 'second') +@@ -556,7 +556,7 @@ class BrowserTest extends \Tests\BrowserTestCase + } + }, + ]) +- ->assertQueryStringHas('foo', '') ++ ->waitForQueryString('foo', '') + ->assertSee('foo', null) + ->waitForLivewire()->click('@button') + ->assertQueryStringHas('foo', '2') +@@ -1093,7 +1093,7 @@ class BrowserTest extends \Tests\BrowserTestCase + } + } + ]) +- ->assertScript('return window.location.search', '?foo[bar]=baz'); ++ ->assertScript('return decodeURIComponent(window.location.search)', '?foo[bar]=baz'); + } + + public function test_it_skips_query_string_encoded_keys_not_tracked_by_livewire() +@@ -1117,7 +1117,7 @@ class BrowserTest extends \Tests\BrowserTestCase + } + } + ]) +- ->assertScript('return window.location.search', '?foo[bar]=baz&bob%5Blob%5D=law'); ++ ->assertScript('return decodeURIComponent(window.location.search)', '?foo[bar]=baz&bob[lob]=law'); + } + + public function test_except_does_remove_value_from_query_string_when_loaded_with_value_then_changed_to_except_value() diff --git a/tasks/livewire__livewire-10767/solution/solve.sh b/tasks/livewire__livewire-10767/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/livewire__livewire-10767/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/livewire__livewire-10767/task.toml b/tasks/livewire__livewire-10767/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..0a06da31539ffed142938f0ac86f73b5d7a856cf --- /dev/null +++ b/tasks/livewire__livewire-10767/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/livewire__livewire-10767" +description = "Stabilize query string browser tests on 3.x" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "livewire", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "livewire/livewire" +ref = "3b2328babd06097f0f606c8fb98aeee3fc1c8610" +reference = "https://github.com/livewire/livewire/pull/10767" +source_access = "auto" +built_at = "2026-11-16T16:09:51.453702+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:6b43e1d8de63a7aeb2efc9ff0e145bbd83bf9ba1b43979b450ee3916368ae028" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-28T18:03:46Z" +diff_format = "unified" +context_files = [ + "src/Features/SupportQueryString/BrowserTest.php", +] +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.431810+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:8e65dcb8bc735c8be50ade49c87e0e05daf889e0f27e553747592d9a49b1ca8e" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/livewire__livewire-10767/tests/capture.py b/tasks/livewire__livewire-10767/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/livewire__livewire-10767/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/livewire__livewire-10767/tests/instruction.md b/tasks/livewire__livewire-10767/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6d9c9bc0492204276ca79ae90cf415686d598d4e --- /dev/null +++ b/tasks/livewire__livewire-10767/tests/instruction.md @@ -0,0 +1,18 @@ +# Issue + +**Title:** Stabilize query string browser tests on 3.x + +## Description + +Backports the query-string browser test hardening already present on 4.x and main. + +- Wait for invalid nullable enum values to settle before asserting the URL +- Decode the browser query string before comparing bracketed keys + +This addresses the two deterministic failures exposed by Chrome 153 in the post-merge 3.x release gate. + +Verified locally with the four affected browser tests passing three consecutive runs (22 assertions each). + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `3b2328babd06`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10767/tests/oracle.patch b/tasks/livewire__livewire-10767/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..5d00d6f0a4e1c5201e03c61ad44db3dee2f0da5c --- /dev/null +++ b/tasks/livewire__livewire-10767/tests/oracle.patch @@ -0,0 +1,40 @@ +diff --git a/src/Features/SupportQueryString/BrowserTest.php b/src/Features/SupportQueryString/BrowserTest.php +index 59d786ec..dbb23de7 100644 +--- a/src/Features/SupportQueryString/BrowserTest.php ++++ b/src/Features/SupportQueryString/BrowserTest.php +@@ -513,7 +513,7 @@ class BrowserTest extends \Tests\BrowserTestCase + } + }, + ]) +- ->assertQueryStringHas('foo', '') ++ ->waitForQueryString('foo', '') + ->assertSee('foo', null) + ->waitForLivewire()->click('@button') + ->assertQueryStringHas('foo', 'second') +@@ -556,7 +556,7 @@ class BrowserTest extends \Tests\BrowserTestCase + } + }, + ]) +- ->assertQueryStringHas('foo', '') ++ ->waitForQueryString('foo', '') + ->assertSee('foo', null) + ->waitForLivewire()->click('@button') + ->assertQueryStringHas('foo', '2') +@@ -1093,7 +1093,7 @@ class BrowserTest extends \Tests\BrowserTestCase + } + } + ]) +- ->assertScript('return window.location.search', '?foo[bar]=baz'); ++ ->assertScript('return decodeURIComponent(window.location.search)', '?foo[bar]=baz'); + } + + public function test_it_skips_query_string_encoded_keys_not_tracked_by_livewire() +@@ -1117,7 +1117,7 @@ class BrowserTest extends \Tests\BrowserTestCase + } + } + ]) +- ->assertScript('return window.location.search', '?foo[bar]=baz&bob%5Blob%5D=law'); ++ ->assertScript('return decodeURIComponent(window.location.search)', '?foo[bar]=baz&bob[lob]=law'); + } + + public function test_except_does_remove_value_from_query_string_when_loaded_with_value_then_changed_to_except_value() diff --git a/tasks/livewire__livewire-10767/tests/test.sh b/tasks/livewire__livewire-10767/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..9b1bb835cf53e085b372b1eb8fb193b6c4ada52d --- /dev/null +++ b/tasks/livewire__livewire-10767/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 3b2328babd06097f0f606c8fb98aeee3fc1c8610 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/livewire__livewire-10767/tests/verifier.py b/tasks/livewire__livewire-10767/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/livewire__livewire-10767/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/livewire__livewire-10773/environment/Dockerfile b/tasks/livewire__livewire-10773/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2b0e159ee8ce195ce98a086105e83d9d0bd84fd4 --- /dev/null +++ b/tasks/livewire__livewire-10773/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/livewire/livewire.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/livewire/livewire.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/livewire/livewire.git +WORKDIR /workspace +RUN git fetch --depth 1 origin d0b4e22841d362dd213ee9602c399594d387b6ee 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard d0b4e22841d362dd213ee9602c399594d387b6ee \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base d0b4e22841d362dd213ee9602c399594d387b6ee \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/livewire__livewire-10773/instruction.md b/tasks/livewire__livewire-10773/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a3f9571d0ac97f0dd0fcfeabf69e7088fc90a1f0 --- /dev/null +++ b/tasks/livewire__livewire-10773/instruction.md @@ -0,0 +1,25 @@ +# Issue + +**Title:** Keep the navigate progress bar above positioned elements while it fades out + +## Description + +When a `wire:navigate` visit finishes, NProgress fades the bar out by lowering the opacity of `#nprogress`. Opacity below 1 turns that wrapper into a stacking context, so the bar's own `z-index: 1031` only applies inside it, and the wrapper itself (no z-index) paints under any positioned element that has one. In an app with a fixed or sticky sidebar, the bar visibly disappears behind the sidebar for the length of the fade. + +This gives the wrapper the same z-index as the bar: + +```css +#nprogress { + pointer-events: none; + position: relative; + z-index: 1031; +} +``` + +`#nprogress` only contains fixed-position children, so it has no box of its own and nothing shifts. + +. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d0b4e22841d3`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10773/solution/patch.diff b/tasks/livewire__livewire-10773/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..c19aa087a779231f5cd5daaea88c6a68145e647b --- /dev/null +++ b/tasks/livewire__livewire-10773/solution/patch.diff @@ -0,0 +1,52 @@ +diff --git a/js/plugins/navigate/bar.js b/js/plugins/navigate/bar.js +index b8a5c271..acf4521c 100644 +--- a/js/plugins/navigate/bar.js ++++ b/js/plugins/navigate/bar.js +@@ -40,6 +40,10 @@ function injectStyles() { + + #nprogress { + pointer-events: none; ++ ++ /* NProgress fades out by setting opacity here, which creates a stacking context... */ ++ position: relative; ++ z-index: 1031; + } + + #nprogress .bar { +diff --git a/src/Features/SupportNavigate/BrowserTest.php b/src/Features/SupportNavigate/BrowserTest.php +index 1a062ef2..1f339754 100644 +--- a/src/Features/SupportNavigate/BrowserTest.php ++++ b/src/Features/SupportNavigate/BrowserTest.php +@@ -408,6 +408,32 @@ class BrowserTest extends \Tests\BrowserTestCase + }); + } + ++ public function test_progress_bar_stays_above_positioned_elements_while_it_fades_out() ++ { ++ $this->browse(function ($browser) { ++ $browser ++ ->visit('/first') ++ ->assertSee('On first') ++ ->assertScript(<<<'JS' ++ (() => { ++ // A fixed sidebar with a z-index, like most app layouts have... ++ let sidebar = document.createElement('div') ++ sidebar.style.cssText = 'position: fixed; top: 0; left: 0; z-index: 20; width: 200px; height: 100px; background: #eee' ++ document.body.prepend(sidebar) ++ ++ // The bar mid fade-out: NProgress fades it by lowering #nprogress's opacity... ++ let progress = document.createElement('div') ++ progress.id = 'nprogress' ++ progress.style.cssText = 'opacity: 0.5; pointer-events: auto' ++ progress.innerHTML = '
' ++ document.body.append(progress) ++ ++ return document.elementFromPoint(50, 1) === progress.querySelector('.bar') ++ })() ++ JS); ++ }); ++ } ++ + public function test_can_navigate_to_page_without_reloading() + { + $this->browse(function ($browser) { diff --git a/tasks/livewire__livewire-10773/solution/solve.sh b/tasks/livewire__livewire-10773/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/livewire__livewire-10773/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/livewire__livewire-10773/task.toml b/tasks/livewire__livewire-10773/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7cf17ccf600fdc13c4b549a1e5e65b336d94559d --- /dev/null +++ b/tasks/livewire__livewire-10773/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/livewire__livewire-10773" +description = "Keep the navigate progress bar above positioned elements while it fades out" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "livewire", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "livewire/livewire" +ref = "d0b4e22841d362dd213ee9602c399594d387b6ee" +reference = "https://github.com/livewire/livewire/pull/10773" +source_access = "auto" +built_at = "2026-11-16T16:09:51.441674+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:b666d7221cf1f9843f359c75e1ee9d1327269d520d273d8577a671440827fba7" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-10-07T11:39:36Z" +diff_format = "unified" +context_files = [ + "js/plugins/navigate/bar.js", + "src/Features/SupportNavigate/BrowserTest.php", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 30 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.432356+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:108fd5bbaa619e83c7b309cc26c21beaddb12766fe0d939f64edd86f874f671a" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/livewire__livewire-10773/tests/capture.py b/tasks/livewire__livewire-10773/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/livewire__livewire-10773/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/livewire__livewire-10773/tests/instruction.md b/tasks/livewire__livewire-10773/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a3f9571d0ac97f0dd0fcfeabf69e7088fc90a1f0 --- /dev/null +++ b/tasks/livewire__livewire-10773/tests/instruction.md @@ -0,0 +1,25 @@ +# Issue + +**Title:** Keep the navigate progress bar above positioned elements while it fades out + +## Description + +When a `wire:navigate` visit finishes, NProgress fades the bar out by lowering the opacity of `#nprogress`. Opacity below 1 turns that wrapper into a stacking context, so the bar's own `z-index: 1031` only applies inside it, and the wrapper itself (no z-index) paints under any positioned element that has one. In an app with a fixed or sticky sidebar, the bar visibly disappears behind the sidebar for the length of the fade. + +This gives the wrapper the same z-index as the bar: + +```css +#nprogress { + pointer-events: none; + position: relative; + z-index: 1031; +} +``` + +`#nprogress` only contains fixed-position children, so it has no box of its own and nothing shifts. + +. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d0b4e22841d3`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10773/tests/oracle.patch b/tasks/livewire__livewire-10773/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..c19aa087a779231f5cd5daaea88c6a68145e647b --- /dev/null +++ b/tasks/livewire__livewire-10773/tests/oracle.patch @@ -0,0 +1,52 @@ +diff --git a/js/plugins/navigate/bar.js b/js/plugins/navigate/bar.js +index b8a5c271..acf4521c 100644 +--- a/js/plugins/navigate/bar.js ++++ b/js/plugins/navigate/bar.js +@@ -40,6 +40,10 @@ function injectStyles() { + + #nprogress { + pointer-events: none; ++ ++ /* NProgress fades out by setting opacity here, which creates a stacking context... */ ++ position: relative; ++ z-index: 1031; + } + + #nprogress .bar { +diff --git a/src/Features/SupportNavigate/BrowserTest.php b/src/Features/SupportNavigate/BrowserTest.php +index 1a062ef2..1f339754 100644 +--- a/src/Features/SupportNavigate/BrowserTest.php ++++ b/src/Features/SupportNavigate/BrowserTest.php +@@ -408,6 +408,32 @@ class BrowserTest extends \Tests\BrowserTestCase + }); + } + ++ public function test_progress_bar_stays_above_positioned_elements_while_it_fades_out() ++ { ++ $this->browse(function ($browser) { ++ $browser ++ ->visit('/first') ++ ->assertSee('On first') ++ ->assertScript(<<<'JS' ++ (() => { ++ // A fixed sidebar with a z-index, like most app layouts have... ++ let sidebar = document.createElement('div') ++ sidebar.style.cssText = 'position: fixed; top: 0; left: 0; z-index: 20; width: 200px; height: 100px; background: #eee' ++ document.body.prepend(sidebar) ++ ++ // The bar mid fade-out: NProgress fades it by lowering #nprogress's opacity... ++ let progress = document.createElement('div') ++ progress.id = 'nprogress' ++ progress.style.cssText = 'opacity: 0.5; pointer-events: auto' ++ progress.innerHTML = '
' ++ document.body.append(progress) ++ ++ return document.elementFromPoint(50, 1) === progress.querySelector('.bar') ++ })() ++ JS); ++ }); ++ } ++ + public function test_can_navigate_to_page_without_reloading() + { + $this->browse(function ($browser) { diff --git a/tasks/livewire__livewire-10773/tests/test.sh b/tasks/livewire__livewire-10773/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..f4255995d98bc2c91067af5b4e4a6a330f30ec75 --- /dev/null +++ b/tasks/livewire__livewire-10773/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace d0b4e22841d362dd213ee9602c399594d387b6ee > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/livewire__livewire-10773/tests/verifier.py b/tasks/livewire__livewire-10773/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/livewire__livewire-10773/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/livewire__livewire-10780/environment/Dockerfile b/tasks/livewire__livewire-10780/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2b0e159ee8ce195ce98a086105e83d9d0bd84fd4 --- /dev/null +++ b/tasks/livewire__livewire-10780/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/livewire/livewire.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/livewire/livewire.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/livewire/livewire.git +WORKDIR /workspace +RUN git fetch --depth 1 origin d0b4e22841d362dd213ee9602c399594d387b6ee 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard d0b4e22841d362dd213ee9602c399594d387b6ee \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base d0b4e22841d362dd213ee9602c399594d387b6ee \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/livewire__livewire-10780/instruction.md b/tasks/livewire__livewire-10780/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..723002a4120e5b4bbbe35344151d7057748d89f6 --- /dev/null +++ b/tasks/livewire__livewire-10780/instruction.md @@ -0,0 +1,21 @@ +# Issue + +**Title:** [4.x] Don't resolve inherited Object.prototype keys on the $wire proxy + +## Description + +. + +The `$wire` proxy checks `property in aliases` and `property in properties`. Both are plain objects, so inherited keys like `constructor` or `toString` match, and the lookup throws: + +```js +$wire.constructor // TypeError: properties[name] is not a function +``` + +This became visible in v4.4.5: the CSP build's evaluator now reads `obj.constructor` on assignment targets, so `x-modelable="$wire.content"` (rendered by `wire:model` on a component with a `#[Modelable]` property) throws on init and the parent-to-child sync never happens when `csp_safe` is enabled. + +This PR uses `Object.hasOwn()` for both lookups, so inherited keys fall through like any other unknown property. A small vitest spec covers it and fails without the fix. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d0b4e22841d3`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10780/solution/patch.diff b/tasks/livewire__livewire-10780/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..6d498a4138bbf3f4e26cb67f89c1d56fec6df90b --- /dev/null +++ b/tasks/livewire__livewire-10780/solution/patch.diff @@ -0,0 +1,38 @@ +diff --git a/js/$wire.js b/js/$wire.js +index 0f7a0f12..78cfaeb2 100644 +--- a/js/$wire.js ++++ b/js/$wire.js +@@ -65,9 +65,9 @@ export function generateWireObject(component, state) { + get(target, property) { + if (property === '__instance') return component + +- if (property in aliases) { ++ if (Object.hasOwn(aliases, property)) { + return getProperty(component, aliases[property]) +- } else if (property in properties) { ++ } else if (Object.hasOwn(properties, property)) { + return getProperty(component, property) + } else if (property in state) { + return state[property] +diff --git a/js/wire.spec.js b/js/wire.spec.js +new file mode 100644 +index 00000000..ae573dc3 +--- /dev/null ++++ b/js/wire.spec.js +@@ -0,0 +1,16 @@ ++import { describe, it, expect } from 'vitest' ++import { generateWireObject } from '@/$wire' ++ ++describe('$wire proxy', () => { ++ it('does not resolve inherited Object.prototype keys as properties or aliases', () => { ++ let $wire = generateWireObject({ id: 'abc' }, { content: 'hello' }) ++ ++ expect(() => $wire.constructor).not.toThrow() ++ expect(() => $wire.toString).not.toThrow() ++ expect(() => $wire.hasOwnProperty).not.toThrow() ++ ++ expect($wire.id).toBe('abc') ++ expect($wire.$id).toBe('abc') ++ expect($wire.content).toBe('hello') ++ }) ++}) diff --git a/tasks/livewire__livewire-10780/solution/solve.sh b/tasks/livewire__livewire-10780/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/livewire__livewire-10780/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/livewire__livewire-10780/task.toml b/tasks/livewire__livewire-10780/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..dee8d5535bfbd349e0863312d550d59fdaf32263 --- /dev/null +++ b/tasks/livewire__livewire-10780/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/livewire__livewire-10780" +description = "[4.x] Don't resolve inherited Object.prototype keys on the $wire proxy" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "livewire", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "livewire/livewire" +ref = "d0b4e22841d362dd213ee9602c399594d387b6ee" +reference = "https://github.com/livewire/livewire/pull/10780" +source_access = "auto" +built_at = "2026-11-16T16:09:51.443162+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:6f4be7565318c027163c3d2e41823efbfb73f2e67af364bde794242982d970c0" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-10-07T11:38:08Z" +diff_format = "unified" +context_files = [ + "js/$wire.js", + "js/wire.spec.js", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 20 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.432910+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:108fd5bbaa619e83c7b309cc26c21beaddb12766fe0d939f64edd86f874f671a" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/livewire__livewire-10780/tests/capture.py b/tasks/livewire__livewire-10780/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/livewire__livewire-10780/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/livewire__livewire-10780/tests/instruction.md b/tasks/livewire__livewire-10780/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..723002a4120e5b4bbbe35344151d7057748d89f6 --- /dev/null +++ b/tasks/livewire__livewire-10780/tests/instruction.md @@ -0,0 +1,21 @@ +# Issue + +**Title:** [4.x] Don't resolve inherited Object.prototype keys on the $wire proxy + +## Description + +. + +The `$wire` proxy checks `property in aliases` and `property in properties`. Both are plain objects, so inherited keys like `constructor` or `toString` match, and the lookup throws: + +```js +$wire.constructor // TypeError: properties[name] is not a function +``` + +This became visible in v4.4.5: the CSP build's evaluator now reads `obj.constructor` on assignment targets, so `x-modelable="$wire.content"` (rendered by `wire:model` on a component with a `#[Modelable]` property) throws on init and the parent-to-child sync never happens when `csp_safe` is enabled. + +This PR uses `Object.hasOwn()` for both lookups, so inherited keys fall through like any other unknown property. A small vitest spec covers it and fails without the fix. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d0b4e22841d3`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-10780/tests/oracle.patch b/tasks/livewire__livewire-10780/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..6d498a4138bbf3f4e26cb67f89c1d56fec6df90b --- /dev/null +++ b/tasks/livewire__livewire-10780/tests/oracle.patch @@ -0,0 +1,38 @@ +diff --git a/js/$wire.js b/js/$wire.js +index 0f7a0f12..78cfaeb2 100644 +--- a/js/$wire.js ++++ b/js/$wire.js +@@ -65,9 +65,9 @@ export function generateWireObject(component, state) { + get(target, property) { + if (property === '__instance') return component + +- if (property in aliases) { ++ if (Object.hasOwn(aliases, property)) { + return getProperty(component, aliases[property]) +- } else if (property in properties) { ++ } else if (Object.hasOwn(properties, property)) { + return getProperty(component, property) + } else if (property in state) { + return state[property] +diff --git a/js/wire.spec.js b/js/wire.spec.js +new file mode 100644 +index 00000000..ae573dc3 +--- /dev/null ++++ b/js/wire.spec.js +@@ -0,0 +1,16 @@ ++import { describe, it, expect } from 'vitest' ++import { generateWireObject } from '@/$wire' ++ ++describe('$wire proxy', () => { ++ it('does not resolve inherited Object.prototype keys as properties or aliases', () => { ++ let $wire = generateWireObject({ id: 'abc' }, { content: 'hello' }) ++ ++ expect(() => $wire.constructor).not.toThrow() ++ expect(() => $wire.toString).not.toThrow() ++ expect(() => $wire.hasOwnProperty).not.toThrow() ++ ++ expect($wire.id).toBe('abc') ++ expect($wire.$id).toBe('abc') ++ expect($wire.content).toBe('hello') ++ }) ++}) diff --git a/tasks/livewire__livewire-10780/tests/test.sh b/tasks/livewire__livewire-10780/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..f4255995d98bc2c91067af5b4e4a6a330f30ec75 --- /dev/null +++ b/tasks/livewire__livewire-10780/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace d0b4e22841d362dd213ee9602c399594d387b6ee > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/livewire__livewire-10780/tests/verifier.py b/tasks/livewire__livewire-10780/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/livewire__livewire-10780/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/livewire__livewire-10781/environment/Dockerfile b/tasks/livewire__livewire-10781/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2b0e159ee8ce195ce98a086105e83d9d0bd84fd4 --- /dev/null +++ b/tasks/livewire__livewire-10781/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/livewire/livewire.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/livewire/livewire.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/livewire/livewire.git +WORKDIR /workspace +RUN git fetch --depth 1 origin d0b4e22841d362dd213ee9602c399594d387b6ee 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard d0b4e22841d362dd213ee9602c399594d387b6ee \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base d0b4e22841d362dd213ee9602c399594d387b6ee \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/livewire__livewire-10781/instruction.md b/tasks/livewire__livewire-10781/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2973fa903f2d8a8bc38c839fc219c74a67c84025 --- /dev/null +++ b/tasks/livewire__livewire-10781/instruction.md @@ -0,0 +1,21 @@ +# Issue + +**Title:** [4.x] Bust the script cache when toggling csp_safe + +## Description + +When assets aren't published, the regular and CSP-safe builds are served from the same route with the same `?id=` version, and that response is cached for a year. So after toggling `csp_safe`, browsers keep running whichever build they already have. Revalidation doesn't help either, since both files in `dist/` share an mtime and the server answers `304`. + +The practical effect: you enable `csp_safe`, everything appears to work, but the browser is still running the `unsafe-eval` build (or the reverse, where expressions the CSP build can't parse keep breaking after you turn it off). + +This PR appends `-csp` to the script's version hash when `csp_safe` is on: + +```html + ++ ++ HTML; ++ } ++ }) ++ ->waitForLivewireToLoad() ++ ->assertSeeIn('@somePropertyWatched', '0') ++ ->waitForLivewire()->click('@increment') ++ ->assertSeeIn('@somePropertyWatched', '1') ++ ->click('@unwatch') ++ ->pause(500) // Give Alpine a moment to process the unwatch ++ ->waitForLivewire()->click('@increment') ++ ->assertSeeIn('@somePropertyWatched', '1'); ++ } ++} diff --git a/tasks/livewire__livewire-9519/solution/solve.sh b/tasks/livewire__livewire-9519/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/livewire__livewire-9519/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/livewire__livewire-9519/task.toml b/tasks/livewire__livewire-9519/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..2a2895a926131e8762466aeb405cae1f17a76a8d --- /dev/null +++ b/tasks/livewire__livewire-9519/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/livewire__livewire-9519" +description = "Return unwatch to unwatch manually if needed" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "livewire", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "livewire/livewire" +ref = "310dedc405ddb24c239d035868bcf6a30acdeca8" +reference = "https://github.com/livewire/livewire/pull/9519" +source_access = "auto" +built_at = "2026-11-16T16:09:51.455343+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:9273ae82f2ba01e09c608fb6a4246112a5088996c3a0079c551c29f9da4a755f" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-01-11T14:54:37Z" +diff_format = "unified" +context_files = [ + "js/$wire.js", + "src/Tests/JavascriptUnwatchBrowserTest.php", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 111 +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.437840+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:c996d625d80965ea9ee18544532be38a3f52703e62cc833c5b61a95d9ed5de66" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/livewire__livewire-9519/tests/capture.py b/tasks/livewire__livewire-9519/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/livewire__livewire-9519/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/livewire__livewire-9519/tests/instruction.md b/tasks/livewire__livewire-9519/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..02d4fe06fb8529938b12aedc0dd35fdc6d77c7dc --- /dev/null +++ b/tasks/livewire__livewire-9519/tests/instruction.md @@ -0,0 +1,77 @@ +# Issue + +**Title:** Return unwatch to unwatch manually if needed + +## Description + +Review the contribution guide first at: https://livewire.laravel.com/docs/contribution-guide + +1️⃣ Is this something that is wanted/needed? Did you create a discussion about it first? +Yes, I have seen the PR #9097, but is not necessary for me to automatically clean up after the element is removed because i will do it with the destroy() function of Alpine.data. + +2️⃣ Did you create a branch for your fix/feature? (Main branch PR's will be closed) +Yes but not in official livewire repository. + +3️⃣ Does it contain multiple, unrelated changes? Please separate the PRs out. +No, only the return unwatch + +4️⃣ Does it include tests? (Required) +Yes, i have tried to do my best for dusk test (first time with dusk, and on windows...) + +5️⃣ Please include a thorough description (including small code snippets if possible) of the improvement and reasons why it's useful. +Sometimes, an Alpine component can use $wire.$watch to observe Livewire properties and execute certain actions related to the Alpine component. However, when the Alpine component is removed (for example, due to a parent Blade condition), the watcher continues to persist, causing errors. I attempted to fix this by using an Alpine.data variable called destroyed, but this only prevents the code from executing—it does not stop the watcher from persisting. + +What i do right now to dodge some errors and re-executing: +```javascript +Alpine.data('myComponent', () => ({ + destroyed: false, + + init() { + this.$wire.$watch('someProperty', (value, old) => { + if (destroyed) return; + this.executeSomething(); + }); + }, + + destroy() { + this.destroyed = true; + }; + + executeSomething() { + if (this.$wire.someProperty == 'something') { + // ... + } + } +})) +``` + +What i want to do by exemple after my PR: +```javascript +Alpine.data('myComponent', () => ({ + unwatch: null, + + init() { + this.unwatch = this.$wire.$watch('someProperty', (value, old) => { + this.executeSomething(); + }); + }, + + destroy() { + if (typeof this.unwatch === 'function') { + this.unwatch(); + } + }; + + executeSomething() { + if (this.$wire.someProperty == 'something') { + // ... + } + } +})) +``` + +Thanks for contributing! 🙌 + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `310dedc405dd`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-9519/tests/oracle.patch b/tasks/livewire__livewire-9519/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..999ca18090278909cdd01009d7c9a5fbf9afa9e4 --- /dev/null +++ b/tasks/livewire__livewire-9519/tests/oracle.patch @@ -0,0 +1,128 @@ +diff --git a/js/$wire.js b/js/$wire.js +index b64ee641..4319b2d9 100644 +--- a/js/$wire.js ++++ b/js/$wire.js +@@ -263,6 +263,8 @@ wireProperty('$watch', (component) => (path, callback) => { + let unwatch = Alpine.watch(getter, callback) + + component.addCleanup(unwatch) ++ ++ return unwatch + }) + + wireProperty('$effect', (component) => (callback) => { +diff --git a/src/Tests/JavascriptUnwatchBrowserTest.php b/src/Tests/JavascriptUnwatchBrowserTest.php +new file mode 100644 +index 00000000..d2027abc +--- /dev/null ++++ b/src/Tests/JavascriptUnwatchBrowserTest.php +@@ -0,0 +1,109 @@ ++someProperty++; ++ } ++ ++ public function render() ++ { ++ return <<<'HTML' ++
++ ++ ++
++ ++ ++
++
++ HTML; ++ } ++ }) ++ ->waitForLivewireToLoad() ++ ->assertSeeIn('@somePropertyWatched', '0') ++ ->waitForLivewire()->click('@increment') ++ ->assertSeeIn('@somePropertyWatched', '1') ++ ->click('@unwatch') ++ ->pause(500) // Give Alpine a moment to process the unwatch ++ ->waitForLivewire()->click('@increment') ++ ->assertSeeIn('@somePropertyWatched', '1'); ++ } ++ ++ public function test_unwatch_works_with_alpine_data_component() ++ { ++ Livewire::visit(new class () extends Component { ++ public int $someProperty = 0; ++ ++ public function increment() ++ { ++ $this->someProperty++; ++ } ++ ++ public function render() ++ { ++ return <<<'HTML' ++
++ ++ ++
++ ++ ++
++ ++ ++
++ HTML; ++ } ++ }) ++ ->waitForLivewireToLoad() ++ ->assertSeeIn('@somePropertyWatched', '0') ++ ->waitForLivewire()->click('@increment') ++ ->assertSeeIn('@somePropertyWatched', '1') ++ ->click('@unwatch') ++ ->pause(500) // Give Alpine a moment to process the unwatch ++ ->waitForLivewire()->click('@increment') ++ ->assertSeeIn('@somePropertyWatched', '1'); ++ } ++} diff --git a/tasks/livewire__livewire-9519/tests/test.sh b/tasks/livewire__livewire-9519/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..cb5625a0b3dce53abf685039f224d12625cb5255 --- /dev/null +++ b/tasks/livewire__livewire-9519/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 310dedc405ddb24c239d035868bcf6a30acdeca8 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/livewire__livewire-9519/tests/verifier.py b/tasks/livewire__livewire-9519/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/livewire__livewire-9519/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/livewire__livewire-9781/environment/Dockerfile b/tasks/livewire__livewire-9781/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2c81ffad8219bb45202465ad6e32940c3fbef15a --- /dev/null +++ b/tasks/livewire__livewire-9781/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/livewire/livewire.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/livewire/livewire.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/livewire/livewire.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 643bef8c8bf7ce08d02867345c8956581f16ba66 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 643bef8c8bf7ce08d02867345c8956581f16ba66 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 643bef8c8bf7ce08d02867345c8956581f16ba66 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/livewire__livewire-9781/instruction.md b/tasks/livewire__livewire-9781/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..fc9160e6ae3a226f2ee5692e287605768c9105d1 --- /dev/null +++ b/tasks/livewire__livewire-9781/instruction.md @@ -0,0 +1,54 @@ +# Issue + +**Title:** Fix `_livewire_component` parameter leaking into URL during SPA navigation + +## Description + +# The Scenario + +When using the `Route::livewire()` macro for full-page components, an internal route parameter leaks into browser URLs during SPA-style navigation: + +```php +Route::livewire('/products', 'pages::products.index')->name('products.index'); +``` + +After navigating with `wire:navigate`, the URL becomes: + +``` +https://example.com/products?_livewire_component=pages::products.index +``` + +Instead of the expected: + +``` +https://example.com/products +``` + +# The Problem + +The `Route::livewire()` macro was storing the component name using Laravel's route defaults mechanism: + +```php +return Route::get($uri, LivewirePageController::class) + ->defaults('_livewire_component', $component); +``` + +Route defaults are designed for default URL parameter values, which means they can be included in URL generation. During SPA navigation, when Livewire fetches the new page and uses `response.url` to update the browser history, this internal parameter was being exposed. + +# The Solution + +Store the component in the route's action array instead of route defaults: + +```php +return tap(Route::get($uri, LivewirePageController::class), function ($route) use ($component) { + $route->action['livewire_component'] = $component; +}); +``` + +The action array is used for route configuration metadata (like route names, middleware, etc.) and is not involved in URL generation, so the parameter can never leak into URLs. + +Fixes: https://github.com/livewire/livewire/discussions/9743 + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `643bef8c8bf7`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-9781/solution/patch.diff b/tasks/livewire__livewire-9781/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..0f9bcbe817479d2eeededc5829a0de82047e6aac --- /dev/null +++ b/tasks/livewire__livewire-9781/solution/patch.diff @@ -0,0 +1,42 @@ +diff --git a/src/Features/SupportPageComponents/SupportPageComponents.php b/src/Features/SupportPageComponents/SupportPageComponents.php +index 9241d610..cb8a6b06 100644 +--- a/src/Features/SupportPageComponents/SupportPageComponents.php ++++ b/src/Features/SupportPageComponents/SupportPageComponents.php +@@ -244,7 +244,7 @@ class SupportPageComponents extends ComponentHook + + // Case 2: Route::livewire macro usage (via LivewirePageController) + if (str($uses)->contains(LivewirePageController::class)) { +- $component = $route->defaults['_livewire_component'] ?? null; ++ $component = $action['livewire_component'] ?? null; + + if (! $component) return false; + +diff --git a/src/Features/SupportRouting/LivewirePageController.php b/src/Features/SupportRouting/LivewirePageController.php +index d7aa2621..9788afcb 100644 +--- a/src/Features/SupportRouting/LivewirePageController.php ++++ b/src/Features/SupportRouting/LivewirePageController.php +@@ -6,7 +6,7 @@ class LivewirePageController + { + public function __invoke() + { +- $component = request()->route()->defaults['_livewire_component']; ++ $component = request()->route()->action['livewire_component']; + + $instance = is_object($component) + ? $component +diff --git a/src/Features/SupportRouting/SupportRouting.php b/src/Features/SupportRouting/SupportRouting.php +index 0d23943d..ed697d7b 100644 +--- a/src/Features/SupportRouting/SupportRouting.php ++++ b/src/Features/SupportRouting/SupportRouting.php +@@ -14,8 +14,9 @@ class SupportRouting extends ComponentHook + app('livewire')->addComponent($component); + } + +- return Route::get($uri, LivewirePageController::class) +- ->defaults('_livewire_component', $component); ++ return tap(Route::get($uri, LivewirePageController::class), function ($route) use ($component) { ++ $route->action['livewire_component'] = $component; ++ }); + }); + } + } diff --git a/tasks/livewire__livewire-9781/solution/solve.sh b/tasks/livewire__livewire-9781/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/livewire__livewire-9781/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/livewire__livewire-9781/task.toml b/tasks/livewire__livewire-9781/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..145cc3c251476a1c84a5b5f85c67e7dc1393c47e --- /dev/null +++ b/tasks/livewire__livewire-9781/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/livewire__livewire-9781" +description = "Fix `_livewire_component` parameter leaking into URL during SPA navigation" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "livewire", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "livewire/livewire" +ref = "643bef8c8bf7ce08d02867345c8956581f16ba66" +reference = "https://github.com/livewire/livewire/pull/9781" +source_access = "auto" +built_at = "2026-11-16T16:09:51.629624+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:888538a04c75ee130640eb23e1650fe61d6d2f48b530a714cf101f7f8a372a65" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-01-21T06:41:33Z" +diff_format = "unified" +context_files = [ + "src/Features/SupportPageComponents/SupportPageComponents.php", + "src/Features/SupportRouting/LivewirePageController.php", + "src/Features/SupportRouting/SupportRouting.php", +] +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.438305+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:c0a1fb66b60203d909a63877ff0ba4d6d65bee2584fe5a19b3ef05fefa36fd46" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/livewire__livewire-9781/tests/capture.py b/tasks/livewire__livewire-9781/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/livewire__livewire-9781/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/livewire__livewire-9781/tests/instruction.md b/tasks/livewire__livewire-9781/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..fc9160e6ae3a226f2ee5692e287605768c9105d1 --- /dev/null +++ b/tasks/livewire__livewire-9781/tests/instruction.md @@ -0,0 +1,54 @@ +# Issue + +**Title:** Fix `_livewire_component` parameter leaking into URL during SPA navigation + +## Description + +# The Scenario + +When using the `Route::livewire()` macro for full-page components, an internal route parameter leaks into browser URLs during SPA-style navigation: + +```php +Route::livewire('/products', 'pages::products.index')->name('products.index'); +``` + +After navigating with `wire:navigate`, the URL becomes: + +``` +https://example.com/products?_livewire_component=pages::products.index +``` + +Instead of the expected: + +``` +https://example.com/products +``` + +# The Problem + +The `Route::livewire()` macro was storing the component name using Laravel's route defaults mechanism: + +```php +return Route::get($uri, LivewirePageController::class) + ->defaults('_livewire_component', $component); +``` + +Route defaults are designed for default URL parameter values, which means they can be included in URL generation. During SPA navigation, when Livewire fetches the new page and uses `response.url` to update the browser history, this internal parameter was being exposed. + +# The Solution + +Store the component in the route's action array instead of route defaults: + +```php +return tap(Route::get($uri, LivewirePageController::class), function ($route) use ($component) { + $route->action['livewire_component'] = $component; +}); +``` + +The action array is used for route configuration metadata (like route names, middleware, etc.) and is not involved in URL generation, so the parameter can never leak into URLs. + +Fixes: https://github.com/livewire/livewire/discussions/9743 + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `643bef8c8bf7`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/livewire__livewire-9781/tests/oracle.patch b/tasks/livewire__livewire-9781/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..0f9bcbe817479d2eeededc5829a0de82047e6aac --- /dev/null +++ b/tasks/livewire__livewire-9781/tests/oracle.patch @@ -0,0 +1,42 @@ +diff --git a/src/Features/SupportPageComponents/SupportPageComponents.php b/src/Features/SupportPageComponents/SupportPageComponents.php +index 9241d610..cb8a6b06 100644 +--- a/src/Features/SupportPageComponents/SupportPageComponents.php ++++ b/src/Features/SupportPageComponents/SupportPageComponents.php +@@ -244,7 +244,7 @@ class SupportPageComponents extends ComponentHook + + // Case 2: Route::livewire macro usage (via LivewirePageController) + if (str($uses)->contains(LivewirePageController::class)) { +- $component = $route->defaults['_livewire_component'] ?? null; ++ $component = $action['livewire_component'] ?? null; + + if (! $component) return false; + +diff --git a/src/Features/SupportRouting/LivewirePageController.php b/src/Features/SupportRouting/LivewirePageController.php +index d7aa2621..9788afcb 100644 +--- a/src/Features/SupportRouting/LivewirePageController.php ++++ b/src/Features/SupportRouting/LivewirePageController.php +@@ -6,7 +6,7 @@ class LivewirePageController + { + public function __invoke() + { +- $component = request()->route()->defaults['_livewire_component']; ++ $component = request()->route()->action['livewire_component']; + + $instance = is_object($component) + ? $component +diff --git a/src/Features/SupportRouting/SupportRouting.php b/src/Features/SupportRouting/SupportRouting.php +index 0d23943d..ed697d7b 100644 +--- a/src/Features/SupportRouting/SupportRouting.php ++++ b/src/Features/SupportRouting/SupportRouting.php +@@ -14,8 +14,9 @@ class SupportRouting extends ComponentHook + app('livewire')->addComponent($component); + } + +- return Route::get($uri, LivewirePageController::class) +- ->defaults('_livewire_component', $component); ++ return tap(Route::get($uri, LivewirePageController::class), function ($route) use ($component) { ++ $route->action['livewire_component'] = $component; ++ }); + }); + } + } diff --git a/tasks/livewire__livewire-9781/tests/test.sh b/tasks/livewire__livewire-9781/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..8bdcf3018749a43f9a6ade389a0a5e957fa5fecb --- /dev/null +++ b/tasks/livewire__livewire-9781/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 643bef8c8bf7ce08d02867345c8956581f16ba66 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/livewire__livewire-9781/tests/verifier.py b/tasks/livewire__livewire-9781/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/livewire__livewire-9781/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/mailcow__mailcow-dockerized-7084/environment/Dockerfile b/tasks/mailcow__mailcow-dockerized-7084/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..0ede5fd2cfaacd241bf2afb0258f8f0149fa6807 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7084/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/mailcow/mailcow-dockerized.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/mailcow/mailcow-dockerized.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/mailcow/mailcow-dockerized.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 7fce984cacb1e040a9e305a671cc9bb418a4da89 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 7fce984cacb1e040a9e305a671cc9bb418a4da89 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 7fce984cacb1e040a9e305a671cc9bb418a4da89 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/mailcow__mailcow-dockerized-7084/instruction.md b/tasks/mailcow__mailcow-dockerized-7084/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b38f9d37aba8d11a42904027420c6275d47a1b0c --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7084/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** [Postfix] update postscreen_access.cidr + +## Description + +This PR updates the postscreen_access.cidr using GitHub Actions and [helper-scripts/update_postscreen_whitelist.sh](https://github.com/mailcow/mailcow-dockerized/blob/master/helper-scripts/update_postscreen_whitelist.sh) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `7fce984cacb1`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/mailcow__mailcow-dockerized-7084/solution/patch.diff b/tasks/mailcow__mailcow-dockerized-7084/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..5e76b24283b9bc012f48bed61b9a4e687f44431c --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7084/solution/patch.diff @@ -0,0 +1,260 @@ +diff --git a/data/conf/postfix/postscreen_access.cidr b/data/conf/postfix/postscreen_access.cidr +index 3d69d686..de38fe39 100644 +--- a/data/conf/postfix/postscreen_access.cidr ++++ b/data/conf/postfix/postscreen_access.cidr +@@ -1,6 +1,6 @@ +-# Whitelist generated by Postwhite v3.4 on Sun Feb 1 00:29:33 UTC 2026 ++# Whitelist generated by Postwhite v3.4 on Sun Mar 1 00:29:01 UTC 2026 + # https://github.com/stevejenkins/postwhite/ +-# 2102 total rules ++# 2174 total rules + 2a00:1450:4000::/36 permit + 2a01:111:f400::/48 permit + 2a01:111:f403:2800::/53 permit +@@ -52,7 +52,11 @@ + 8.25.194.0/23 permit + 8.25.196.0/23 permit + 8.36.116.0/24 permit ++8.39.54.0/23 permit ++8.39.54.250/31 permit + 8.39.144.0/24 permit ++8.40.222.0/23 permit ++8.40.222.250/31 permit + 12.130.86.238 permit + 13.107.213.51 permit + 13.107.246.51 permit +@@ -65,6 +69,7 @@ + 13.111.191.0/24 permit + 13.216.7.111 permit + 13.216.54.180 permit ++13.247.164.219 permit + 15.200.21.50 permit + 15.200.44.248 permit + 15.200.201.185 permit +@@ -168,6 +173,7 @@ + 34.215.104.144 permit + 34.218.115.239 permit + 34.225.212.172 permit ++34.241.242.183 permit + 35.83.148.184 permit + 35.155.198.111 permit + 35.158.23.94 permit +@@ -191,6 +197,7 @@ + 40.233.64.216 permit + 40.233.83.78 permit + 40.233.88.28 permit ++43.239.212.33 permit + 44.206.138.57 permit + 44.210.169.44 permit + 44.217.45.156 permit +@@ -272,6 +279,7 @@ + 50.112.246.219 permit + 52.1.14.157 permit + 52.5.230.59 permit ++52.6.74.205 permit + 52.12.53.23 permit + 52.13.214.179 permit + 52.26.1.71 permit +@@ -328,6 +336,7 @@ + 54.244.54.130 permit + 54.244.242.0/24 permit + 54.255.61.23 permit ++56.124.6.228 permit + 57.103.64.0/18 permit + 57.129.93.249 permit + 62.13.128.0/24 permit +@@ -393,6 +402,7 @@ + 65.110.161.77 permit + 65.123.29.213 permit + 65.123.29.220 permit ++65.154.166.0/24 permit + 65.212.180.36 permit + 66.102.0.0/20 permit + 66.119.150.192/26 permit +@@ -697,7 +707,9 @@ + 87.248.117.205 permit + 87.253.232.0/21 permit + 89.22.108.0/24 permit +-91.198.2.0/24 permit ++91.198.2.177 permit ++91.198.2.217 permit ++91.198.2.222 permit + 91.211.240.0/22 permit + 94.236.119.0/26 permit + 95.131.104.0/21 permit +@@ -1194,6 +1206,9 @@ + 99.78.197.208/28 permit + 103.9.96.0/22 permit + 103.28.42.0/24 permit ++103.84.217.15 permit ++103.84.217.238 permit ++103.89.75.238 permit + 103.151.192.0/23 permit + 103.168.172.128/27 permit + 103.237.104.0/22 permit +@@ -1354,6 +1369,9 @@ + 117.120.16.0/21 permit + 119.42.242.52/31 permit + 119.42.242.156 permit ++121.244.91.48 permit ++121.244.91.52 permit ++122.15.156.182 permit + 123.126.78.64/29 permit + 124.108.96.24/31 permit + 124.108.96.28/31 permit +@@ -1419,7 +1437,21 @@ + 134.170.141.64/26 permit + 134.170.143.0/24 permit + 134.170.174.0/24 permit ++135.84.80.0/24 permit ++135.84.81.0/24 permit ++135.84.82.0/24 permit ++135.84.83.0/24 permit + 135.84.216.0/22 permit ++136.143.160.0/24 permit ++136.143.161.0/24 permit ++136.143.162.0/24 permit ++136.143.176.0/24 permit ++136.143.177.0/24 permit ++136.143.178.49 permit ++136.143.182.0/23 permit ++136.143.184.0/24 permit ++136.143.188.0/24 permit ++136.143.190.0/23 permit + 136.146.128.0/20 permit + 136.147.128.0/20 permit + 136.147.135.0/24 permit +@@ -1435,6 +1467,7 @@ + 139.138.46.219 permit + 139.138.57.55 permit + 139.138.58.119 permit ++139.167.79.86 permit + 139.180.17.0/24 permit + 140.238.148.191 permit + 141.148.55.217 permit +@@ -1523,8 +1556,10 @@ + 159.135.224.0/20 permit + 159.135.228.10 permit + 159.183.0.0/16 permit ++159.183.14.233 permit + 159.183.68.71 permit + 159.183.79.38 permit ++159.183.121.182 permit + 159.183.129.172 permit + 160.1.62.192 permit + 161.38.192.0/20 permit +@@ -1550,6 +1585,10 @@ + 164.152.23.32 permit + 164.152.25.241 permit + 164.177.132.168/30 permit ++165.173.128.0/24 permit ++165.173.180.1 permit ++165.173.180.250/31 permit ++165.173.182.250/31 permit + 166.78.68.0/22 permit + 166.78.68.221 permit + 166.78.69.169 permit +@@ -1579,6 +1618,18 @@ + 168.245.12.252 permit + 168.245.46.9 permit + 168.245.127.231 permit ++169.148.129.0/24 permit ++169.148.131.0/24 permit ++169.148.138.0/24 permit ++169.148.142.10 permit ++169.148.142.33 permit ++169.148.144.0/25 permit ++169.148.144.10 permit ++169.148.146.0/23 permit ++169.148.175.3 permit ++169.148.179.3 permit ++169.148.188.0/24 permit ++169.148.188.182 permit + 170.9.232.254 permit + 170.10.128.0/24 permit + 170.10.129.0/24 permit +@@ -1612,8 +1663,7 @@ + 182.50.78.64/28 permit + 183.240.219.64/29 permit + 185.4.120.0/22 permit +-185.11.253.128/27 permit +-185.11.255.0/24 permit ++185.11.255.144 permit + 185.12.80.0/22 permit + 185.28.196.0/22 permit + 185.58.84.93 permit +@@ -1627,8 +1677,16 @@ + 185.138.56.128/25 permit + 185.189.236.0/22 permit + 185.211.120.0/22 permit +-185.233.188.0/23 permit +-185.233.190.0/23 permit ++185.233.188.68 permit ++185.233.188.75 permit ++185.233.188.84 permit ++185.233.188.160 permit ++185.233.188.176 permit ++185.233.188.247 permit ++185.233.189.44 permit ++185.233.189.98 permit ++185.233.189.122 permit ++185.233.189.228 permit + 185.250.236.0/22 permit + 185.250.239.148 permit + 185.250.239.168 permit +@@ -1704,7 +1762,9 @@ + 193.109.254.0/23 permit + 193.122.128.100 permit + 193.123.56.63 permit +-193.142.157.0/24 permit ++193.142.157.15 permit ++193.142.157.125 permit ++193.142.157.158 permit + 193.142.157.191 permit + 193.142.157.198 permit + 194.19.134.0/25 permit +@@ -1764,7 +1824,16 @@ + 199.16.156.0/22 permit + 199.33.145.1 permit + 199.33.145.32 permit ++199.34.22.36 permit + 199.59.148.0/22 permit ++199.67.80.2 permit ++199.67.80.20 permit ++199.67.82.2 permit ++199.67.82.20 permit ++199.67.84.0/24 permit ++199.67.86.0/24 permit ++199.67.88.0/24 permit ++199.67.90.0/24 permit + 199.101.161.130 permit + 199.101.162.0/25 permit + 199.122.120.0/21 permit +@@ -1820,6 +1889,8 @@ + 204.92.114.187 permit + 204.92.114.203 permit + 204.92.114.204/31 permit ++204.141.32.0/23 permit ++204.141.42.0/23 permit + 204.216.164.202 permit + 204.220.160.0/21 permit + 204.220.168.0/21 permit +@@ -1997,8 +2068,6 @@ + 212.227.126.225 permit + 212.227.126.226 permit + 212.227.126.227 permit +-213.95.19.64/27 permit +-213.95.135.4 permit + 213.199.128.139 permit + 213.199.128.145 permit + 213.199.138.181 permit +@@ -2088,6 +2157,9 @@ + 2001:748:400:3301::3 permit + 2001:748:400:3301::4 permit + 2404:6800:4000::/36 permit ++2607:13c0:0001:0000:0000:0000:0000:7000/116 permit ++2607:13c0:0002:0000:0000:0000:0000:1000/116 permit ++2607:13c0:0004:0000:0000:0000:0000:0000/116 permit + 2607:f8b0:4000::/36 permit + 2620:109:c003:104::/64 permit + 2620:109:c003:104::215 permit diff --git a/tasks/mailcow__mailcow-dockerized-7084/solution/solve.sh b/tasks/mailcow__mailcow-dockerized-7084/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7084/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/mailcow__mailcow-dockerized-7084/task.toml b/tasks/mailcow__mailcow-dockerized-7084/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..525b20b96588577be12df325ebf139fd6a134455 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7084/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/mailcow__mailcow-dockerized-7084" +description = "[Postfix] update postscreen_access.cidr" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "mailcow-dockerized", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "mailcow/mailcow-dockerized" +ref = "7fce984cacb1e040a9e305a671cc9bb418a4da89" +reference = "https://github.com/mailcow/mailcow-dockerized/pull/7084" +source_access = "auto" +built_at = "2026-11-16T16:09:53.237796+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:7863df6e323f1025621885f2d3a537ac4c79c024efa5e0f9b74c4fa8f8f9808c" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-03-01T12:30:57Z" +diff_format = "unified" +context_files = [ + "data/conf/postfix/postscreen_access.cidr", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 92 +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.438794+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:62529f5f9ff59fff76550c49b0af273b4554710e29c7e6ab624de828078f99f8" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/mailcow__mailcow-dockerized-7084/tests/capture.py b/tasks/mailcow__mailcow-dockerized-7084/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7084/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/mailcow__mailcow-dockerized-7084/tests/instruction.md b/tasks/mailcow__mailcow-dockerized-7084/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b38f9d37aba8d11a42904027420c6275d47a1b0c --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7084/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** [Postfix] update postscreen_access.cidr + +## Description + +This PR updates the postscreen_access.cidr using GitHub Actions and [helper-scripts/update_postscreen_whitelist.sh](https://github.com/mailcow/mailcow-dockerized/blob/master/helper-scripts/update_postscreen_whitelist.sh) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `7fce984cacb1`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/mailcow__mailcow-dockerized-7084/tests/oracle.patch b/tasks/mailcow__mailcow-dockerized-7084/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..5e76b24283b9bc012f48bed61b9a4e687f44431c --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7084/tests/oracle.patch @@ -0,0 +1,260 @@ +diff --git a/data/conf/postfix/postscreen_access.cidr b/data/conf/postfix/postscreen_access.cidr +index 3d69d686..de38fe39 100644 +--- a/data/conf/postfix/postscreen_access.cidr ++++ b/data/conf/postfix/postscreen_access.cidr +@@ -1,6 +1,6 @@ +-# Whitelist generated by Postwhite v3.4 on Sun Feb 1 00:29:33 UTC 2026 ++# Whitelist generated by Postwhite v3.4 on Sun Mar 1 00:29:01 UTC 2026 + # https://github.com/stevejenkins/postwhite/ +-# 2102 total rules ++# 2174 total rules + 2a00:1450:4000::/36 permit + 2a01:111:f400::/48 permit + 2a01:111:f403:2800::/53 permit +@@ -52,7 +52,11 @@ + 8.25.194.0/23 permit + 8.25.196.0/23 permit + 8.36.116.0/24 permit ++8.39.54.0/23 permit ++8.39.54.250/31 permit + 8.39.144.0/24 permit ++8.40.222.0/23 permit ++8.40.222.250/31 permit + 12.130.86.238 permit + 13.107.213.51 permit + 13.107.246.51 permit +@@ -65,6 +69,7 @@ + 13.111.191.0/24 permit + 13.216.7.111 permit + 13.216.54.180 permit ++13.247.164.219 permit + 15.200.21.50 permit + 15.200.44.248 permit + 15.200.201.185 permit +@@ -168,6 +173,7 @@ + 34.215.104.144 permit + 34.218.115.239 permit + 34.225.212.172 permit ++34.241.242.183 permit + 35.83.148.184 permit + 35.155.198.111 permit + 35.158.23.94 permit +@@ -191,6 +197,7 @@ + 40.233.64.216 permit + 40.233.83.78 permit + 40.233.88.28 permit ++43.239.212.33 permit + 44.206.138.57 permit + 44.210.169.44 permit + 44.217.45.156 permit +@@ -272,6 +279,7 @@ + 50.112.246.219 permit + 52.1.14.157 permit + 52.5.230.59 permit ++52.6.74.205 permit + 52.12.53.23 permit + 52.13.214.179 permit + 52.26.1.71 permit +@@ -328,6 +336,7 @@ + 54.244.54.130 permit + 54.244.242.0/24 permit + 54.255.61.23 permit ++56.124.6.228 permit + 57.103.64.0/18 permit + 57.129.93.249 permit + 62.13.128.0/24 permit +@@ -393,6 +402,7 @@ + 65.110.161.77 permit + 65.123.29.213 permit + 65.123.29.220 permit ++65.154.166.0/24 permit + 65.212.180.36 permit + 66.102.0.0/20 permit + 66.119.150.192/26 permit +@@ -697,7 +707,9 @@ + 87.248.117.205 permit + 87.253.232.0/21 permit + 89.22.108.0/24 permit +-91.198.2.0/24 permit ++91.198.2.177 permit ++91.198.2.217 permit ++91.198.2.222 permit + 91.211.240.0/22 permit + 94.236.119.0/26 permit + 95.131.104.0/21 permit +@@ -1194,6 +1206,9 @@ + 99.78.197.208/28 permit + 103.9.96.0/22 permit + 103.28.42.0/24 permit ++103.84.217.15 permit ++103.84.217.238 permit ++103.89.75.238 permit + 103.151.192.0/23 permit + 103.168.172.128/27 permit + 103.237.104.0/22 permit +@@ -1354,6 +1369,9 @@ + 117.120.16.0/21 permit + 119.42.242.52/31 permit + 119.42.242.156 permit ++121.244.91.48 permit ++121.244.91.52 permit ++122.15.156.182 permit + 123.126.78.64/29 permit + 124.108.96.24/31 permit + 124.108.96.28/31 permit +@@ -1419,7 +1437,21 @@ + 134.170.141.64/26 permit + 134.170.143.0/24 permit + 134.170.174.0/24 permit ++135.84.80.0/24 permit ++135.84.81.0/24 permit ++135.84.82.0/24 permit ++135.84.83.0/24 permit + 135.84.216.0/22 permit ++136.143.160.0/24 permit ++136.143.161.0/24 permit ++136.143.162.0/24 permit ++136.143.176.0/24 permit ++136.143.177.0/24 permit ++136.143.178.49 permit ++136.143.182.0/23 permit ++136.143.184.0/24 permit ++136.143.188.0/24 permit ++136.143.190.0/23 permit + 136.146.128.0/20 permit + 136.147.128.0/20 permit + 136.147.135.0/24 permit +@@ -1435,6 +1467,7 @@ + 139.138.46.219 permit + 139.138.57.55 permit + 139.138.58.119 permit ++139.167.79.86 permit + 139.180.17.0/24 permit + 140.238.148.191 permit + 141.148.55.217 permit +@@ -1523,8 +1556,10 @@ + 159.135.224.0/20 permit + 159.135.228.10 permit + 159.183.0.0/16 permit ++159.183.14.233 permit + 159.183.68.71 permit + 159.183.79.38 permit ++159.183.121.182 permit + 159.183.129.172 permit + 160.1.62.192 permit + 161.38.192.0/20 permit +@@ -1550,6 +1585,10 @@ + 164.152.23.32 permit + 164.152.25.241 permit + 164.177.132.168/30 permit ++165.173.128.0/24 permit ++165.173.180.1 permit ++165.173.180.250/31 permit ++165.173.182.250/31 permit + 166.78.68.0/22 permit + 166.78.68.221 permit + 166.78.69.169 permit +@@ -1579,6 +1618,18 @@ + 168.245.12.252 permit + 168.245.46.9 permit + 168.245.127.231 permit ++169.148.129.0/24 permit ++169.148.131.0/24 permit ++169.148.138.0/24 permit ++169.148.142.10 permit ++169.148.142.33 permit ++169.148.144.0/25 permit ++169.148.144.10 permit ++169.148.146.0/23 permit ++169.148.175.3 permit ++169.148.179.3 permit ++169.148.188.0/24 permit ++169.148.188.182 permit + 170.9.232.254 permit + 170.10.128.0/24 permit + 170.10.129.0/24 permit +@@ -1612,8 +1663,7 @@ + 182.50.78.64/28 permit + 183.240.219.64/29 permit + 185.4.120.0/22 permit +-185.11.253.128/27 permit +-185.11.255.0/24 permit ++185.11.255.144 permit + 185.12.80.0/22 permit + 185.28.196.0/22 permit + 185.58.84.93 permit +@@ -1627,8 +1677,16 @@ + 185.138.56.128/25 permit + 185.189.236.0/22 permit + 185.211.120.0/22 permit +-185.233.188.0/23 permit +-185.233.190.0/23 permit ++185.233.188.68 permit ++185.233.188.75 permit ++185.233.188.84 permit ++185.233.188.160 permit ++185.233.188.176 permit ++185.233.188.247 permit ++185.233.189.44 permit ++185.233.189.98 permit ++185.233.189.122 permit ++185.233.189.228 permit + 185.250.236.0/22 permit + 185.250.239.148 permit + 185.250.239.168 permit +@@ -1704,7 +1762,9 @@ + 193.109.254.0/23 permit + 193.122.128.100 permit + 193.123.56.63 permit +-193.142.157.0/24 permit ++193.142.157.15 permit ++193.142.157.125 permit ++193.142.157.158 permit + 193.142.157.191 permit + 193.142.157.198 permit + 194.19.134.0/25 permit +@@ -1764,7 +1824,16 @@ + 199.16.156.0/22 permit + 199.33.145.1 permit + 199.33.145.32 permit ++199.34.22.36 permit + 199.59.148.0/22 permit ++199.67.80.2 permit ++199.67.80.20 permit ++199.67.82.2 permit ++199.67.82.20 permit ++199.67.84.0/24 permit ++199.67.86.0/24 permit ++199.67.88.0/24 permit ++199.67.90.0/24 permit + 199.101.161.130 permit + 199.101.162.0/25 permit + 199.122.120.0/21 permit +@@ -1820,6 +1889,8 @@ + 204.92.114.187 permit + 204.92.114.203 permit + 204.92.114.204/31 permit ++204.141.32.0/23 permit ++204.141.42.0/23 permit + 204.216.164.202 permit + 204.220.160.0/21 permit + 204.220.168.0/21 permit +@@ -1997,8 +2068,6 @@ + 212.227.126.225 permit + 212.227.126.226 permit + 212.227.126.227 permit +-213.95.19.64/27 permit +-213.95.135.4 permit + 213.199.128.139 permit + 213.199.128.145 permit + 213.199.138.181 permit +@@ -2088,6 +2157,9 @@ + 2001:748:400:3301::3 permit + 2001:748:400:3301::4 permit + 2404:6800:4000::/36 permit ++2607:13c0:0001:0000:0000:0000:0000:7000/116 permit ++2607:13c0:0002:0000:0000:0000:0000:1000/116 permit ++2607:13c0:0004:0000:0000:0000:0000:0000/116 permit + 2607:f8b0:4000::/36 permit + 2620:109:c003:104::/64 permit + 2620:109:c003:104::215 permit diff --git a/tasks/mailcow__mailcow-dockerized-7084/tests/test.sh b/tasks/mailcow__mailcow-dockerized-7084/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ff0bfa14904042360b5c135cf19468a21d9a4fbb --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7084/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 7fce984cacb1e040a9e305a671cc9bb418a4da89 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/mailcow__mailcow-dockerized-7084/tests/verifier.py b/tasks/mailcow__mailcow-dockerized-7084/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7084/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/mailcow__mailcow-dockerized-7086/environment/Dockerfile b/tasks/mailcow__mailcow-dockerized-7086/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..1221bed56b7161a38180b8bebc7d4d41b74f7fa6 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7086/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/mailcow/mailcow-dockerized.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/mailcow/mailcow-dockerized.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/mailcow/mailcow-dockerized.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 5e478a32df91bac32f9cbb150aad6dd0228f8240 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 5e478a32df91bac32f9cbb150aad6dd0228f8240 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 5e478a32df91bac32f9cbb150aad6dd0228f8240 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/mailcow__mailcow-dockerized-7086/instruction.md b/tasks/mailcow__mailcow-dockerized-7086/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9af50b33b0b6dd5746cf283e0f19d699d2578ec5 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7086/instruction.md @@ -0,0 +1,42 @@ +# Issue + +**Title:** [SOGo] Build SOGo from source with security patches + +## Description + + + +## Contribution Guidelines + +* [x] I've read the [contribution guidelines](https://github.com/mailcow/mailcow-dockerized/blob/master/CONTRIBUTING.md) and wholeheartedly agree them + +## What does this PR include? + +### Short Description + +This PR modifies the SOGo Docker image to build from source instead of using pre-compiled packages from Alinto's repository. The primary motivation is that Alinto does not include security patches in their official packages in a timely manner, leaving systems vulnerable to known security issues. + +The implementation uses a source-based build with git cherry-pick support to apply critical security patches before official releases. + +**Key changes:** +- Single-stage Dockerfile building +- Git cherry-pick mechanism for applying security patches to stable releases + +**Benefits:** +- Apply security patches immediately without waiting for official packages +- Easy addition of future patches via `SOGO_SECURITY_PATCHES` ARG + +### Affected Containers + +- sogo-mailcow + +## Did you run tests? + +### What did you tested? + +- Docker image builds successfully from source +- SOGo daemon starts and runs properly + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `5e478a32df91`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/mailcow__mailcow-dockerized-7086/solution/patch.diff b/tasks/mailcow__mailcow-dockerized-7086/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..b541a006f47e5075bf83a0b5ba2d372c1249d236 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7086/solution/patch.diff @@ -0,0 +1,215 @@ +diff --git a/data/Dockerfiles/sogo/Dockerfile b/data/Dockerfiles/sogo/Dockerfile +index ed7e07ed..8ec90ae3 100644 +--- a/data/Dockerfiles/sogo/Dockerfile ++++ b/data/Dockerfiles/sogo/Dockerfile +@@ -1,47 +1,161 @@ +-FROM debian:bookworm-slim ++# SOGo built from source to enable security patch application ++# Repository: https://github.com/Alinto/sogo ++# Version: SOGo-5.12.4 ++# ++# Applied security patches: ++# - 16ab99e7cf8db2c30b211f0d5e338d7f9e3a9efb: XSS vulnerability in theme parameter ++# ++# To add new patches, modify SOGO_SECURITY_PATCHES ARG below with space-separated commit hashes ++ ++FROM debian:bookworm + + LABEL maintainer="The Infrastructure Company GmbH " + + ARG DEBIAN_FRONTEND=noninteractive +-ARG DEBIAN_VERSION=bookworm +-ARG SOGO_DEBIAN_REPOSITORY=https://packagingv2.sogo.nu/sogo-nightly-debian/ ++ARG SOGO_VERSION=SOGo-5.12.4 ++ARG SOPE_VERSION=SOPE-5.12.4 ++# Security patches to apply (space-separated commit hashes) ++ARG SOGO_SECURITY_PATCHES="16ab99e7cf8db2c30b211f0d5e338d7f9e3a9efb" + # renovate: datasource=github-releases depName=tianon/gosu versioning=semver-coerced extractVersion=^(?.*)$ + ARG GOSU_VERSION=1.19 + ENV LC_ALL=C + +-# Prerequisites +-RUN echo "Building from repository $SOGO_DEBIAN_REPOSITORY" \ +- && apt-get update && apt-get install -y --no-install-recommends \ +- apt-transport-https \ +- ca-certificates \ +- gettext \ +- gnupg \ +- mariadb-client \ +- rsync \ +- supervisor \ +- syslog-ng \ +- syslog-ng-core \ +- syslog-ng-mod-redis \ +- dirmngr \ +- netcat-traditional \ +- psmisc \ +- wget \ +- patch \ ++# Install dependencies, build SOPE and SOGo, then clean up (all in one layer to minimize image size) ++RUN apt-get update && apt-get install -y --no-install-recommends \ ++ # Build dependencies ++ git \ ++ build-essential \ ++ gobjc \ ++ gnustep-make \ ++ gnustep-base-runtime \ ++ libgnustep-base-dev \ ++ libxml2-dev \ ++ libldap2-dev \ ++ libssl-dev \ ++ zlib1g-dev \ ++ libpq-dev \ ++ libmariadb-dev-compat \ ++ libmemcached-dev \ ++ libsodium-dev \ ++ libcurl4-openssl-dev \ ++ libzip-dev \ ++ libytnef0-dev \ ++ curl \ ++ ca-certificates \ ++ # Runtime dependencies ++ apt-transport-https \ ++ gettext \ ++ gnupg \ ++ mariadb-client \ ++ rsync \ ++ supervisor \ ++ syslog-ng \ ++ syslog-ng-core \ ++ syslog-ng-mod-redis \ ++ dirmngr \ ++ netcat-traditional \ ++ psmisc \ ++ wget \ ++ patch \ ++ libobjc4 \ ++ libxml2 \ ++ libldap-2.5-0 \ ++ libssl3 \ ++ zlib1g \ ++ libmariadb3 \ ++ libmemcached11 \ ++ libsodium23 \ ++ libcurl4 \ ++ libzip4 \ ++ libytnef0 \ ++ # Download gosu + && dpkgArch="$(dpkg --print-architecture | awk -F- '{ print $NF }')" \ + && wget -O /usr/local/bin/gosu "https://github.com/tianon/gosu/releases/download/$GOSU_VERSION/gosu-$dpkgArch" \ + && chmod +x /usr/local/bin/gosu \ + && gosu nobody true \ +- && mkdir /usr/share/doc/sogo \ +- && touch /usr/share/doc/sogo/empty.sh \ +- && wget -O- https://keys.openpgp.org/vks/v1/by-fingerprint/74FFC6D72B925A34B5D356BDF8A27B36A6E2EAE9 | gpg --dearmor | apt-key add - \ +- && echo "deb [trusted=yes] ${SOGO_DEBIAN_REPOSITORY} ${DEBIAN_VERSION} main" > /etc/apt/sources.list.d/sogo.list \ +- && apt-get update && apt-get install -y --no-install-recommends \ +- sogo \ +- sogo-activesync \ +- && apt-get autoclean \ ++ # Build SOPE ++ && git clone --depth 1 --branch ${SOPE_VERSION} https://github.com/Alinto/sope.git /tmp/sope \ ++ && cd /tmp/sope \ ++ && rm -rf .git \ ++ && . /usr/share/GNUstep/Makefiles/GNUstep.sh \ ++ && ./configure --prefix=/usr --disable-debug --disable-strip \ ++ && make -j$(nproc) \ ++ && make install \ ++ && cd / \ ++ && rm -rf /tmp/sope \ ++ # Build SOGo with security patches ++ && git clone --depth 1 --branch ${SOGO_VERSION} https://github.com/Alinto/sogo.git /tmp/sogo \ ++ && cd /tmp/sogo \ ++ && git config user.email "builder@mailcow.local" \ ++ && git config user.name "SOGo Builder" \ ++ && for patch in ${SOGO_SECURITY_PATCHES}; do \ ++ echo "Applying security patch: ${patch}"; \ ++ git fetch origin ${patch} && git cherry-pick ${patch}; \ ++ done \ ++ && rm -rf .git \ ++ && . /usr/share/GNUstep/Makefiles/GNUstep.sh \ ++ && ./configure --disable-debug --disable-strip \ ++ && make -j$(nproc) \ ++ && make install \ ++ && cd / \ ++ && rm -rf /tmp/sogo \ ++ # Strip binaries ++ && strip --strip-unneeded /usr/local/sbin/sogod 2>/dev/null || true \ ++ && strip --strip-unneeded /usr/local/sbin/sogo-tool 2>/dev/null || true \ ++ && strip --strip-unneeded /usr/local/sbin/sogo-ealarms-notify 2>/dev/null || true \ ++ && strip --strip-unneeded /usr/local/sbin/sogo-slapd-sockd 2>/dev/null || true \ ++ # Remove build dependencies and clean up ++ && apt-get purge -y --auto-remove \ ++ git \ ++ build-essential \ ++ gobjc \ ++ gnustep-make \ ++ libgnustep-base-dev \ ++ libxml2-dev \ ++ libldap2-dev \ ++ libssl-dev \ ++ zlib1g-dev \ ++ libpq-dev \ ++ libmariadb-dev-compat \ ++ libmemcached-dev \ ++ libsodium-dev \ ++ libcurl4-openssl-dev \ ++ libzip-dev \ ++ libytnef0-dev \ ++ curl \ ++ && apt-get autoremove -y \ ++ && apt-get clean \ + && rm -rf /var/lib/apt/lists/* \ ++ && rm -rf /usr/share/doc/* \ ++ && rm -rf /usr/share/man/* \ ++ && rm -rf /var/cache/debconf/* \ ++ && rm -rf /tmp/* \ ++ && rm -rf /root/.cache \ ++ && find /usr/local/lib -name '*.a' -delete \ ++ && find /usr/lib -name '*.a' -delete \ ++ && mkdir -p /usr/share/doc/sogo \ ++ && touch /usr/share/doc/sogo/empty.sh \ + && touch /etc/default/locale + ++# Configure library paths ++RUN echo "/usr/lib64" > /etc/ld.so.conf.d/sogo.conf \ ++ && echo "/usr/local/lib/sogo" >> /etc/ld.so.conf.d/sogo.conf \ ++ && echo "/usr/local/lib/GNUstep/Frameworks/SOGo.framework/Versions/5/sogo" >> /etc/ld.so.conf.d/sogo.conf \ ++ && ldconfig ++ ++# Create sogo user and group ++RUN groupadd -r -g 999 sogo \ ++ && useradd -r -u 999 -g sogo -d /var/lib/sogo -s /bin/bash -c "SOGo Daemon" sogo \ ++ && mkdir -p /var/lib/sogo /var/run/sogo /var/log/sogo \ ++ && chown -R sogo:sogo /var/lib/sogo /var/run/sogo /var/log/sogo ++ ++# Create symlinks for SOGo binaries ++RUN ln -s /usr/local/sbin/sogod /usr/sbin/sogod \ ++ && ln -s /usr/local/sbin/sogo-tool /usr/sbin/sogo-tool \ ++ && ln -s /usr/local/sbin/sogo-ealarms-notify /usr/sbin/sogo-ealarms-notify \ ++ && ln -s /usr/local/sbin/sogo-slapd-sockd /usr/sbin/sogo-slapd-sockd ++ ++# Copy configuration files and scripts + COPY ./bootstrap-sogo.sh /bootstrap-sogo.sh + COPY syslog-ng.conf /etc/syslog-ng/syslog-ng.conf + COPY syslog-ng-redis_slave.conf /etc/syslog-ng/syslog-ng-redis_slave.conf +@@ -56,4 +170,4 @@ RUN chmod +x /bootstrap-sogo.sh \ + + ENTRYPOINT ["/docker-entrypoint.sh"] + +-CMD ["/usr/bin/supervisord", "-c", "/etc/supervisor/supervisord.conf"] +\ No newline at end of file ++CMD ["/usr/bin/supervisord", "-c", "/etc/supervisor/supervisord.conf"] +diff --git a/docker-compose.yml b/docker-compose.yml +index 75cca872..cebdd91c 100644 +--- a/docker-compose.yml ++++ b/docker-compose.yml +@@ -200,7 +200,7 @@ services: + - phpfpm + + sogo-mailcow: +- image: ghcr.io/mailcow/sogo:5.12.4-1 ++ image: ghcr.io/mailcow/sogo:5.12.4-2 + environment: + - DBNAME=${DBNAME} + - DBUSER=${DBUSER} diff --git a/tasks/mailcow__mailcow-dockerized-7086/solution/solve.sh b/tasks/mailcow__mailcow-dockerized-7086/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7086/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/mailcow__mailcow-dockerized-7086/task.toml b/tasks/mailcow__mailcow-dockerized-7086/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..accb3c8f954193afc52bb5154cc4dbb3da456012 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7086/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/mailcow__mailcow-dockerized-7086" +description = "[SOGo] Build SOGo from source with security patches" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "mailcow-dockerized", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "mailcow/mailcow-dockerized" +ref = "5e478a32df91bac32f9cbb150aad6dd0228f8240" +reference = "https://github.com/mailcow/mailcow-dockerized/pull/7086" +source_access = "auto" +built_at = "2026-11-16T16:09:53.212266+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:e73ce66361299209ff5b7ddb16d4660406035818576cfe953eed9f605efa68ac" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-03-03T13:24:29Z" +diff_format = "unified" +context_files = [ + "data/Dockerfiles/sogo/Dockerfile", + "docker-compose.yml", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 176 +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.439266+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:7ae661a347d9b2ab9880caebb93194daf1298aaa38d4d3ea0405c9781f61a39b" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/mailcow__mailcow-dockerized-7086/tests/capture.py b/tasks/mailcow__mailcow-dockerized-7086/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7086/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/mailcow__mailcow-dockerized-7086/tests/instruction.md b/tasks/mailcow__mailcow-dockerized-7086/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9af50b33b0b6dd5746cf283e0f19d699d2578ec5 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7086/tests/instruction.md @@ -0,0 +1,42 @@ +# Issue + +**Title:** [SOGo] Build SOGo from source with security patches + +## Description + + + +## Contribution Guidelines + +* [x] I've read the [contribution guidelines](https://github.com/mailcow/mailcow-dockerized/blob/master/CONTRIBUTING.md) and wholeheartedly agree them + +## What does this PR include? + +### Short Description + +This PR modifies the SOGo Docker image to build from source instead of using pre-compiled packages from Alinto's repository. The primary motivation is that Alinto does not include security patches in their official packages in a timely manner, leaving systems vulnerable to known security issues. + +The implementation uses a source-based build with git cherry-pick support to apply critical security patches before official releases. + +**Key changes:** +- Single-stage Dockerfile building +- Git cherry-pick mechanism for applying security patches to stable releases + +**Benefits:** +- Apply security patches immediately without waiting for official packages +- Easy addition of future patches via `SOGO_SECURITY_PATCHES` ARG + +### Affected Containers + +- sogo-mailcow + +## Did you run tests? + +### What did you tested? + +- Docker image builds successfully from source +- SOGo daemon starts and runs properly + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `5e478a32df91`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/mailcow__mailcow-dockerized-7086/tests/oracle.patch b/tasks/mailcow__mailcow-dockerized-7086/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..b541a006f47e5075bf83a0b5ba2d372c1249d236 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7086/tests/oracle.patch @@ -0,0 +1,215 @@ +diff --git a/data/Dockerfiles/sogo/Dockerfile b/data/Dockerfiles/sogo/Dockerfile +index ed7e07ed..8ec90ae3 100644 +--- a/data/Dockerfiles/sogo/Dockerfile ++++ b/data/Dockerfiles/sogo/Dockerfile +@@ -1,47 +1,161 @@ +-FROM debian:bookworm-slim ++# SOGo built from source to enable security patch application ++# Repository: https://github.com/Alinto/sogo ++# Version: SOGo-5.12.4 ++# ++# Applied security patches: ++# - 16ab99e7cf8db2c30b211f0d5e338d7f9e3a9efb: XSS vulnerability in theme parameter ++# ++# To add new patches, modify SOGO_SECURITY_PATCHES ARG below with space-separated commit hashes ++ ++FROM debian:bookworm + + LABEL maintainer="The Infrastructure Company GmbH " + + ARG DEBIAN_FRONTEND=noninteractive +-ARG DEBIAN_VERSION=bookworm +-ARG SOGO_DEBIAN_REPOSITORY=https://packagingv2.sogo.nu/sogo-nightly-debian/ ++ARG SOGO_VERSION=SOGo-5.12.4 ++ARG SOPE_VERSION=SOPE-5.12.4 ++# Security patches to apply (space-separated commit hashes) ++ARG SOGO_SECURITY_PATCHES="16ab99e7cf8db2c30b211f0d5e338d7f9e3a9efb" + # renovate: datasource=github-releases depName=tianon/gosu versioning=semver-coerced extractVersion=^(?.*)$ + ARG GOSU_VERSION=1.19 + ENV LC_ALL=C + +-# Prerequisites +-RUN echo "Building from repository $SOGO_DEBIAN_REPOSITORY" \ +- && apt-get update && apt-get install -y --no-install-recommends \ +- apt-transport-https \ +- ca-certificates \ +- gettext \ +- gnupg \ +- mariadb-client \ +- rsync \ +- supervisor \ +- syslog-ng \ +- syslog-ng-core \ +- syslog-ng-mod-redis \ +- dirmngr \ +- netcat-traditional \ +- psmisc \ +- wget \ +- patch \ ++# Install dependencies, build SOPE and SOGo, then clean up (all in one layer to minimize image size) ++RUN apt-get update && apt-get install -y --no-install-recommends \ ++ # Build dependencies ++ git \ ++ build-essential \ ++ gobjc \ ++ gnustep-make \ ++ gnustep-base-runtime \ ++ libgnustep-base-dev \ ++ libxml2-dev \ ++ libldap2-dev \ ++ libssl-dev \ ++ zlib1g-dev \ ++ libpq-dev \ ++ libmariadb-dev-compat \ ++ libmemcached-dev \ ++ libsodium-dev \ ++ libcurl4-openssl-dev \ ++ libzip-dev \ ++ libytnef0-dev \ ++ curl \ ++ ca-certificates \ ++ # Runtime dependencies ++ apt-transport-https \ ++ gettext \ ++ gnupg \ ++ mariadb-client \ ++ rsync \ ++ supervisor \ ++ syslog-ng \ ++ syslog-ng-core \ ++ syslog-ng-mod-redis \ ++ dirmngr \ ++ netcat-traditional \ ++ psmisc \ ++ wget \ ++ patch \ ++ libobjc4 \ ++ libxml2 \ ++ libldap-2.5-0 \ ++ libssl3 \ ++ zlib1g \ ++ libmariadb3 \ ++ libmemcached11 \ ++ libsodium23 \ ++ libcurl4 \ ++ libzip4 \ ++ libytnef0 \ ++ # Download gosu + && dpkgArch="$(dpkg --print-architecture | awk -F- '{ print $NF }')" \ + && wget -O /usr/local/bin/gosu "https://github.com/tianon/gosu/releases/download/$GOSU_VERSION/gosu-$dpkgArch" \ + && chmod +x /usr/local/bin/gosu \ + && gosu nobody true \ +- && mkdir /usr/share/doc/sogo \ +- && touch /usr/share/doc/sogo/empty.sh \ +- && wget -O- https://keys.openpgp.org/vks/v1/by-fingerprint/74FFC6D72B925A34B5D356BDF8A27B36A6E2EAE9 | gpg --dearmor | apt-key add - \ +- && echo "deb [trusted=yes] ${SOGO_DEBIAN_REPOSITORY} ${DEBIAN_VERSION} main" > /etc/apt/sources.list.d/sogo.list \ +- && apt-get update && apt-get install -y --no-install-recommends \ +- sogo \ +- sogo-activesync \ +- && apt-get autoclean \ ++ # Build SOPE ++ && git clone --depth 1 --branch ${SOPE_VERSION} https://github.com/Alinto/sope.git /tmp/sope \ ++ && cd /tmp/sope \ ++ && rm -rf .git \ ++ && . /usr/share/GNUstep/Makefiles/GNUstep.sh \ ++ && ./configure --prefix=/usr --disable-debug --disable-strip \ ++ && make -j$(nproc) \ ++ && make install \ ++ && cd / \ ++ && rm -rf /tmp/sope \ ++ # Build SOGo with security patches ++ && git clone --depth 1 --branch ${SOGO_VERSION} https://github.com/Alinto/sogo.git /tmp/sogo \ ++ && cd /tmp/sogo \ ++ && git config user.email "builder@mailcow.local" \ ++ && git config user.name "SOGo Builder" \ ++ && for patch in ${SOGO_SECURITY_PATCHES}; do \ ++ echo "Applying security patch: ${patch}"; \ ++ git fetch origin ${patch} && git cherry-pick ${patch}; \ ++ done \ ++ && rm -rf .git \ ++ && . /usr/share/GNUstep/Makefiles/GNUstep.sh \ ++ && ./configure --disable-debug --disable-strip \ ++ && make -j$(nproc) \ ++ && make install \ ++ && cd / \ ++ && rm -rf /tmp/sogo \ ++ # Strip binaries ++ && strip --strip-unneeded /usr/local/sbin/sogod 2>/dev/null || true \ ++ && strip --strip-unneeded /usr/local/sbin/sogo-tool 2>/dev/null || true \ ++ && strip --strip-unneeded /usr/local/sbin/sogo-ealarms-notify 2>/dev/null || true \ ++ && strip --strip-unneeded /usr/local/sbin/sogo-slapd-sockd 2>/dev/null || true \ ++ # Remove build dependencies and clean up ++ && apt-get purge -y --auto-remove \ ++ git \ ++ build-essential \ ++ gobjc \ ++ gnustep-make \ ++ libgnustep-base-dev \ ++ libxml2-dev \ ++ libldap2-dev \ ++ libssl-dev \ ++ zlib1g-dev \ ++ libpq-dev \ ++ libmariadb-dev-compat \ ++ libmemcached-dev \ ++ libsodium-dev \ ++ libcurl4-openssl-dev \ ++ libzip-dev \ ++ libytnef0-dev \ ++ curl \ ++ && apt-get autoremove -y \ ++ && apt-get clean \ + && rm -rf /var/lib/apt/lists/* \ ++ && rm -rf /usr/share/doc/* \ ++ && rm -rf /usr/share/man/* \ ++ && rm -rf /var/cache/debconf/* \ ++ && rm -rf /tmp/* \ ++ && rm -rf /root/.cache \ ++ && find /usr/local/lib -name '*.a' -delete \ ++ && find /usr/lib -name '*.a' -delete \ ++ && mkdir -p /usr/share/doc/sogo \ ++ && touch /usr/share/doc/sogo/empty.sh \ + && touch /etc/default/locale + ++# Configure library paths ++RUN echo "/usr/lib64" > /etc/ld.so.conf.d/sogo.conf \ ++ && echo "/usr/local/lib/sogo" >> /etc/ld.so.conf.d/sogo.conf \ ++ && echo "/usr/local/lib/GNUstep/Frameworks/SOGo.framework/Versions/5/sogo" >> /etc/ld.so.conf.d/sogo.conf \ ++ && ldconfig ++ ++# Create sogo user and group ++RUN groupadd -r -g 999 sogo \ ++ && useradd -r -u 999 -g sogo -d /var/lib/sogo -s /bin/bash -c "SOGo Daemon" sogo \ ++ && mkdir -p /var/lib/sogo /var/run/sogo /var/log/sogo \ ++ && chown -R sogo:sogo /var/lib/sogo /var/run/sogo /var/log/sogo ++ ++# Create symlinks for SOGo binaries ++RUN ln -s /usr/local/sbin/sogod /usr/sbin/sogod \ ++ && ln -s /usr/local/sbin/sogo-tool /usr/sbin/sogo-tool \ ++ && ln -s /usr/local/sbin/sogo-ealarms-notify /usr/sbin/sogo-ealarms-notify \ ++ && ln -s /usr/local/sbin/sogo-slapd-sockd /usr/sbin/sogo-slapd-sockd ++ ++# Copy configuration files and scripts + COPY ./bootstrap-sogo.sh /bootstrap-sogo.sh + COPY syslog-ng.conf /etc/syslog-ng/syslog-ng.conf + COPY syslog-ng-redis_slave.conf /etc/syslog-ng/syslog-ng-redis_slave.conf +@@ -56,4 +170,4 @@ RUN chmod +x /bootstrap-sogo.sh \ + + ENTRYPOINT ["/docker-entrypoint.sh"] + +-CMD ["/usr/bin/supervisord", "-c", "/etc/supervisor/supervisord.conf"] +\ No newline at end of file ++CMD ["/usr/bin/supervisord", "-c", "/etc/supervisor/supervisord.conf"] +diff --git a/docker-compose.yml b/docker-compose.yml +index 75cca872..cebdd91c 100644 +--- a/docker-compose.yml ++++ b/docker-compose.yml +@@ -200,7 +200,7 @@ services: + - phpfpm + + sogo-mailcow: +- image: ghcr.io/mailcow/sogo:5.12.4-1 ++ image: ghcr.io/mailcow/sogo:5.12.4-2 + environment: + - DBNAME=${DBNAME} + - DBUSER=${DBUSER} diff --git a/tasks/mailcow__mailcow-dockerized-7086/tests/test.sh b/tasks/mailcow__mailcow-dockerized-7086/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..21fa278de7d27b1baeb5484f54a69b6cb01ef7c2 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7086/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 5e478a32df91bac32f9cbb150aad6dd0228f8240 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/mailcow__mailcow-dockerized-7086/tests/verifier.py b/tasks/mailcow__mailcow-dockerized-7086/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7086/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/mailcow__mailcow-dockerized-7088/environment/Dockerfile b/tasks/mailcow__mailcow-dockerized-7088/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..44be1e182701475923ae83cf86514aeeebf3727f --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7088/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/mailcow/mailcow-dockerized.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/mailcow/mailcow-dockerized.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/mailcow/mailcow-dockerized.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4abb5cbfabf7245e04a0e8a213a95d49d58e6b22 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4abb5cbfabf7245e04a0e8a213a95d49d58e6b22 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4abb5cbfabf7245e04a0e8a213a95d49d58e6b22 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/mailcow__mailcow-dockerized-7088/instruction.md b/tasks/mailcow__mailcow-dockerized-7088/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..64be031691989471c69eca55830a20734ad29fcf --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7088/instruction.md @@ -0,0 +1,38 @@ +# Issue + +**Title:** [Web] Add missing EAS and DAV protocol options to mailbox bulk actions + +## Description + + + +## Contribution Guidelines + +* [x] I've read the [contribution guidelines](https://github.com/mailcow/mailcow-dockerized/blob/master/CONTRIBUTING.md) and wholeheartedly agree them + + + +## What does this PR include? + +### Short Description + +Adds missing ActiveSync (EAS) and CalDAV/CardDAV (DAV) protocol options to mailbox bulk action dropdowns. These protocol options were available in individual mailbox editing but missing from bulk actions, creating an inconsistency in the admin interface. + +Fixes: +- #7043 + +### Affected Containers + +- None (template-only change) + +## Did you run tests? + +### What did you tested? + +- Verified EAS and DAV options appear in both mobile and desktop bulk action dropdowns +- Tested bulk enable/disable of EAS protocol on multiple mailboxes +- Tested bulk enable/disable of DAV protocol on multiple mailboxes + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4abb5cbfabf7`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/mailcow__mailcow-dockerized-7088/solution/patch.diff b/tasks/mailcow__mailcow-dockerized-7088/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..e6d173acc100cfd5d7899e069f922d350b13b150 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7088/solution/patch.diff @@ -0,0 +1,57 @@ +diff --git a/data/web/templates/mailbox/tab-mailboxes.twig b/data/web/templates/mailbox/tab-mailboxes.twig +index fce7d627..6a176cda 100644 +--- a/data/web/templates/mailbox/tab-mailboxes.twig ++++ b/data/web/templates/mailbox/tab-mailboxes.twig +@@ -58,6 +58,14 @@ + +
  • {{ lang.mailbox.activate }}
  • +
  • {{ lang.mailbox.deactivate }}
  • ++
  • ++ ++
  • {{ lang.mailbox.activate }}
  • ++
  • {{ lang.mailbox.deactivate }}
  • ++
  • ++ ++
  • {{ lang.mailbox.activate }}
  • ++
  • {{ lang.mailbox.deactivate }}
  • + + {{ lang.mailbox.add_mailbox }} + +@@ -104,9 +112,18 @@ + +
  • {{ lang.mailbox.activate }}
  • +
  • {{ lang.mailbox.deactivate }}
  • ++
  • + +
  • {{ lang.mailbox.activate }}
  • +
  • {{ lang.mailbox.deactivate }}
  • ++
  • ++ ++
  • {{ lang.mailbox.activate }}
  • ++
  • {{ lang.mailbox.deactivate }}
  • ++
  • ++ ++
  • {{ lang.mailbox.activate }}
  • ++
  • {{ lang.mailbox.deactivate }}
  • + + + +
    diff --git a/tasks/mailcow__mailcow-dockerized-7088/solution/solve.sh b/tasks/mailcow__mailcow-dockerized-7088/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7088/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/mailcow__mailcow-dockerized-7088/task.toml b/tasks/mailcow__mailcow-dockerized-7088/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..dd98b1f4ba923da1ff2c5b1467a265bc36a99e50 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7088/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/mailcow__mailcow-dockerized-7088" +description = "[Web] Add missing EAS and DAV protocol options to mailbox bulk actions" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "mailcow-dockerized", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "mailcow/mailcow-dockerized" +ref = "4abb5cbfabf7245e04a0e8a213a95d49d58e6b22" +reference = "https://github.com/mailcow/mailcow-dockerized/pull/7088" +source_access = "auto" +built_at = "2026-11-16T16:09:53.241590+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:91c6604e820f523db8df2bdf67ddb9de6af5bbab49fe2a99103f9bb0a984c7a1" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-03-03T13:42:50Z" +diff_format = "unified" +context_files = [ + "data/web/templates/mailbox/tab-mailboxes.twig", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 26 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.439750+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:4e98104e59815766ebd10e73d137827ee98d82231d5c6d100a78a8f42565a3af" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/mailcow__mailcow-dockerized-7088/tests/capture.py b/tasks/mailcow__mailcow-dockerized-7088/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7088/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/mailcow__mailcow-dockerized-7088/tests/instruction.md b/tasks/mailcow__mailcow-dockerized-7088/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..64be031691989471c69eca55830a20734ad29fcf --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7088/tests/instruction.md @@ -0,0 +1,38 @@ +# Issue + +**Title:** [Web] Add missing EAS and DAV protocol options to mailbox bulk actions + +## Description + + + +## Contribution Guidelines + +* [x] I've read the [contribution guidelines](https://github.com/mailcow/mailcow-dockerized/blob/master/CONTRIBUTING.md) and wholeheartedly agree them + + + +## What does this PR include? + +### Short Description + +Adds missing ActiveSync (EAS) and CalDAV/CardDAV (DAV) protocol options to mailbox bulk action dropdowns. These protocol options were available in individual mailbox editing but missing from bulk actions, creating an inconsistency in the admin interface. + +Fixes: +- #7043 + +### Affected Containers + +- None (template-only change) + +## Did you run tests? + +### What did you tested? + +- Verified EAS and DAV options appear in both mobile and desktop bulk action dropdowns +- Tested bulk enable/disable of EAS protocol on multiple mailboxes +- Tested bulk enable/disable of DAV protocol on multiple mailboxes + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4abb5cbfabf7`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/mailcow__mailcow-dockerized-7088/tests/oracle.patch b/tasks/mailcow__mailcow-dockerized-7088/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..e6d173acc100cfd5d7899e069f922d350b13b150 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7088/tests/oracle.patch @@ -0,0 +1,57 @@ +diff --git a/data/web/templates/mailbox/tab-mailboxes.twig b/data/web/templates/mailbox/tab-mailboxes.twig +index fce7d627..6a176cda 100644 +--- a/data/web/templates/mailbox/tab-mailboxes.twig ++++ b/data/web/templates/mailbox/tab-mailboxes.twig +@@ -58,6 +58,14 @@ + +
  • {{ lang.mailbox.activate }}
  • +
  • {{ lang.mailbox.deactivate }}
  • ++
  • ++ ++
  • {{ lang.mailbox.activate }}
  • ++
  • {{ lang.mailbox.deactivate }}
  • ++
  • ++ ++
  • {{ lang.mailbox.activate }}
  • ++
  • {{ lang.mailbox.deactivate }}
  • + + {{ lang.mailbox.add_mailbox }} +
    +@@ -104,9 +112,18 @@ + +
  • {{ lang.mailbox.activate }}
  • +
  • {{ lang.mailbox.deactivate }}
  • ++
  • + +
  • {{ lang.mailbox.activate }}
  • +
  • {{ lang.mailbox.deactivate }}
  • ++
  • ++ ++
  • {{ lang.mailbox.activate }}
  • ++
  • {{ lang.mailbox.deactivate }}
  • ++
  • ++ ++
  • {{ lang.mailbox.activate }}
  • ++
  • {{ lang.mailbox.deactivate }}
  • + + + +
    diff --git a/tasks/mailcow__mailcow-dockerized-7088/tests/test.sh b/tasks/mailcow__mailcow-dockerized-7088/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..85e658de9374c86fb97216dc6110562f7bc3ead9 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7088/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 4abb5cbfabf7245e04a0e8a213a95d49d58e6b22 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/mailcow__mailcow-dockerized-7088/tests/verifier.py b/tasks/mailcow__mailcow-dockerized-7088/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7088/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/mailcow__mailcow-dockerized-7089/environment/Dockerfile b/tasks/mailcow__mailcow-dockerized-7089/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6fae70b9c39d5b52a2a037955b83c82131154afb --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7089/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/mailcow/mailcow-dockerized.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/mailcow/mailcow-dockerized.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/mailcow/mailcow-dockerized.git +WORKDIR /workspace +RUN git fetch --depth 1 origin bccfcefd1773e491ac99a9d44649b6d59ee97055 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard bccfcefd1773e491ac99a9d44649b6d59ee97055 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base bccfcefd1773e491ac99a9d44649b6d59ee97055 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/mailcow__mailcow-dockerized-7089/instruction.md b/tasks/mailcow__mailcow-dockerized-7089/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..908184ab3da86da218dc632a9987421036c8ba60 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7089/instruction.md @@ -0,0 +1,36 @@ +# Issue + +**Title:** [Web] switch from GET to POST for datatable requests + +## Description + + + +## Contribution Guidelines + +* [x] I've read the [contribution guidelines](https://github.com/mailcow/mailcow-dockerized/blob/master/CONTRIBUTING.md) and wholeheartedly agree them + + + +## What does this PR include? + +### Short Description + +This PR switches Datatable search requests from GET to POST method to prevent URI length limitation errors . GET requests can hit URL length limits when searching with complex queries or large datasets, resulting in failed searches or truncated results. + +Fixes: +- + +### Affected Containers + +- None + +## Did you run tests? + +### What did you tested? + +- Datatable search functionality across all admin pages (mailboxes, domains, aliases, etc.) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `bccfcefd1773`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/mailcow__mailcow-dockerized-7089/solution/patch.diff b/tasks/mailcow__mailcow-dockerized-7089/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..bac5930284c7ca950c0c7ef3c86cb5f3578fba49 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7089/solution/patch.diff @@ -0,0 +1,331 @@ +diff --git a/data/web/inc/sessions.inc.php b/data/web/inc/sessions.inc.php +index 8f3192d7..ac308b68 100644 +--- a/data/web/inc/sessions.inc.php ++++ b/data/web/inc/sessions.inc.php +@@ -140,17 +140,32 @@ function session_check() { + ); + return false; + } +- if (!empty($_POST)) { +- if ($_SESSION['CSRF']['TOKEN'] != $_POST['csrf_token']) { +- $_SESSION['return'][] = array( +- 'type' => 'warning', +- 'msg' => 'session_token' +- ); +- return false; ++ // Check if this is a POST request (form-encoded or JSON) ++ $is_post_request = !empty($_POST) || ( ++ isset($_SERVER['CONTENT_TYPE']) && ++ strpos($_SERVER['CONTENT_TYPE'], 'application/json') !== false ++ ); ++ ++ if ($is_post_request) { ++ // Skip CSRF check for DataTables server-side processing endpoints ++ // These are read-only operations (equivalent to GET) authenticated by session ++ $is_search_endpoint = ( ++ isset($_GET['query']) && ++ preg_match('#^search/(domain|mailbox)$#', $_GET['query']) ++ ); ++ ++ if (!$is_search_endpoint && !empty($_POST)) { ++ if ($_SESSION['CSRF']['TOKEN'] != $_POST['csrf_token']) { ++ $_SESSION['return'][] = array( ++ 'type' => 'warning', ++ 'msg' => 'session_token' ++ ); ++ return false; ++ } ++ unset($_POST['csrf_token']); ++ $_SESSION['CSRF']['TOKEN'] = bin2hex(random_bytes(32)); ++ $_SESSION['CSRF']['TIME'] = time(); + } +- unset($_POST['csrf_token']); +- $_SESSION['CSRF']['TOKEN'] = bin2hex(random_bytes(32)); +- $_SESSION['CSRF']['TIME'] = time(); + } + return true; + } +diff --git a/data/web/js/site/mailbox.js b/data/web/js/site/mailbox.js +index 7010077d..e8edb994 100644 +--- a/data/web/js/site/mailbox.js ++++ b/data/web/js/site/mailbox.js +@@ -471,8 +471,13 @@ jQuery(function($){ + hideTableExpandCollapseBtn('#tab-domains', '#domain_table'); + }, + ajax: { +- type: "GET", +- url: "/api/v1/get/domain/datatables", ++ type: "POST", ++ url: "/api/v1/search/domain", ++ contentType: "application/json", ++ processData: false, ++ data: function(d) { ++ return JSON.stringify(d); ++ }, + dataSrc: function(json){ + $.each(json.data, function(i, item) { + item.domain_name = escapeHtml(item.domain_name); +@@ -898,8 +903,13 @@ jQuery(function($){ + hideTableExpandCollapseBtn('#tab-mailboxes', '#mailbox_table'); + }, + ajax: { +- type: "GET", +- url: "/api/v1/get/mailbox/datatables", ++ type: "POST", ++ url: "/api/v1/search/mailbox", ++ contentType: "application/json", ++ processData: false, ++ data: function(d) { ++ return JSON.stringify(d); ++ }, + dataSrc: function(json){ + $.each(json.data, function (i, item) { + item.quota = { +diff --git a/data/web/json_api.php b/data/web/json_api.php +index 5409e65d..41f1d265 100644 +--- a/data/web/json_api.php ++++ b/data/web/json_api.php +@@ -91,6 +91,11 @@ if (isset($_GET['query'])) { + if ($action == 'delete') { + $_POST['items'] = $request; + } ++ ++ // search ++ if ($action == 'search') { ++ // placeholder for search, as the request body is already decoded and available in $requestDecoded ++ } + } + api_log($_POST); + +@@ -457,47 +462,6 @@ if (isset($_GET['query'])) { + + case "domain": + switch ($object) { +- case "datatables": +- $table = ['domain', 'd']; +- $primaryKey = 'domain'; +- $columns = [ +- ['db' => 'domain', 'dt' => 2], +- ['db' => 'aliases', 'dt' => 3, 'order_subquery' => "SELECT COUNT(*) FROM `alias` WHERE (`domain`= `d`.`domain` OR `domain` IN (SELECT `alias_domain` FROM `alias_domain` WHERE `target_domain` = `d`.`domain`)) AND `address` NOT IN (SELECT `username` FROM `mailbox`)"], +- ['db' => 'mailboxes', 'dt' => 4, 'order_subquery' => "SELECT COUNT(*) FROM `mailbox` WHERE `mailbox`.`domain` = `d`.`domain` AND (`mailbox`.`kind` = '' OR `mailbox`.`kind` = NULL)"], +- ['db' => 'quota', 'dt' => 5, 'order_subquery' => "SELECT COALESCE(SUM(`mailbox`.`quota`), 0) FROM `mailbox` WHERE `mailbox`.`domain` = `d`.`domain` AND (`mailbox`.`kind` = '' OR `mailbox`.`kind` = NULL)"], +- ['db' => 'stats', 'dt' => 6, 'dummy' => true, 'order_subquery' => "SELECT SUM(bytes) FROM `quota2` WHERE `quota2`.`username` IN (SELECT `username` FROM `mailbox` WHERE `domain` = `d`.`domain`)"], +- ['db' => 'defquota', 'dt' => 7], +- ['db' => 'maxquota', 'dt' => 8], +- ['db' => 'backupmx', 'dt' => 10], +- ['db' => 'tags', 'dt' => 14, 'dummy' => true, 'search' => ['join' => 'LEFT JOIN `tags_domain` AS `td` ON `td`.`domain` = `d`.`domain`', 'where_column' => '`td`.`tag_name`']], +- ['db' => 'active', 'dt' => 15], +- ]; +- +- require_once $_SERVER['DOCUMENT_ROOT'] . '/inc/lib/ssp.class.php'; +- global $pdo; +- if($_SESSION['mailcow_cc_role'] === 'admin') { +- $data = SSP::simple($_GET, $pdo, $table, $primaryKey, $columns); +- } elseif ($_SESSION['mailcow_cc_role'] === 'domainadmin') { +- $data = SSP::complex($_GET, $pdo, $table, $primaryKey, $columns, +- 'INNER JOIN domain_admins as da ON da.domain = d.domain', +- [ +- 'condition' => 'da.active = 1 and da.username = :username', +- 'bindings' => ['username' => $_SESSION['mailcow_cc_username']] +- ]); +- } +- +- if (!empty($data['data'])) { +- $domainsData = []; +- foreach ($data['data'] as $domain) { +- if ($details = mailbox('get', 'domain_details', $domain[2])) { +- $domainsData[] = $details; +- } +- } +- $data['data'] = $domainsData; +- } +- +- process_get_return($data); +- break; + case "all": + $tags = null; + if (isset($_GET['tags']) && $_GET['tags'] != '') +@@ -997,46 +961,6 @@ if (isset($_GET['query'])) { + break; + case "mailbox": + switch ($object) { +- case "datatables": +- $table = ['mailbox', 'm']; +- $primaryKey = 'username'; +- $columns = [ +- ['db' => 'username', 'dt' => 2], +- ['db' => 'quota', 'dt' => 3], +- ['db' => 'last_mail_login', 'dt' => 4, 'dummy' => true, 'order_subquery' => "SELECT MAX(`datetime`) FROM `sasl_log` WHERE `service` != 'SSO' AND `username` = `m`.`username`"], +- ['db' => 'last_pw_change', 'dt' => 5, 'dummy' => true, 'order_subquery' => "JSON_EXTRACT(attributes, '$.passwd_update')"], +- ['db' => 'in_use', 'dt' => 6, 'dummy' => true, 'order_subquery' => "(SELECT SUM(bytes) FROM `quota2` WHERE `quota2`.`username` = `m`.`username`) / `m`.`quota`"], +- ['db' => 'name', 'dt' => 7], +- ['db' => 'messages', 'dt' => 20, 'dummy' => true, 'order_subquery' => "SELECT SUM(messages) FROM `quota2` WHERE `quota2`.`username` = `m`.`username`"], +- ['db' => 'tags', 'dt' => 23, 'dummy' => true, 'search' => ['join' => 'LEFT JOIN `tags_mailbox` AS `tm` ON `tm`.`username` = `m`.`username`', 'where_column' => '`tm`.`tag_name`']], +- ['db' => 'active', 'dt' => 24], +- ]; +- +- require_once $_SERVER['DOCUMENT_ROOT'] . '/inc/lib/ssp.class.php'; +- global $pdo; +- if($_SESSION['mailcow_cc_role'] === 'admin') { +- $data = SSP::complex($_GET, $pdo, $table, $primaryKey, $columns, null, "(`m`.`kind` = '' OR `m`.`kind` = NULL)"); +- } elseif ($_SESSION['mailcow_cc_role'] === 'domainadmin') { +- $data = SSP::complex($_GET, $pdo, $table, $primaryKey, $columns, +- 'INNER JOIN domain_admins as da ON da.domain = m.domain', +- [ +- 'condition' => "(`m`.`kind` = '' OR `m`.`kind` = NULL) AND `da`.`active` = 1 AND `da`.`username` = :username", +- 'bindings' => ['username' => $_SESSION['mailcow_cc_username']] +- ]); +- } +- +- if (!empty($data['data'])) { +- $mailboxData = []; +- foreach ($data['data'] as $mailbox) { +- if ($details = mailbox('get', 'mailbox_details', $mailbox[2])) { +- $mailboxData[] = $details; +- } +- } +- $data['data'] = $mailboxData; +- } +- +- process_get_return($data); +- break; + case "all": + case "reduced": + $tags = null; +@@ -1625,6 +1549,136 @@ if (isset($_GET['query'])) { + } + } + break; ++ case "search": ++ function process_search_return($return) { ++ if ($return === false) { ++ echo json_encode(array( ++ 'type' => 'error', ++ 'msg' => 'Cannot get item' ++ )); ++ } ++ else { ++ echo json_encode($return, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT); ++ } ++ } ++ // only allow POST requests to SEARCH API endpoints ++ if ($_SERVER['REQUEST_METHOD'] != 'POST') { ++ http_response_code(405); ++ echo json_encode(array( ++ 'type' => 'error', ++ 'msg' => 'only POST method is allowed' ++ )); ++ exit(); ++ } ++ ++ // Load SSP class ++ require_once $_SERVER['DOCUMENT_ROOT'] . '/inc/lib/ssp.class.php'; ++ global $pdo; ++ ++ switch ($category) { ++ case "domain": ++ $table = ['domain', 'd']; ++ $primaryKey = 'domain'; ++ $columns = [ ++ ['db' => 'domain', 'dt' => 2], ++ ['db' => 'aliases', 'dt' => 3, 'order_subquery' => "SELECT COUNT(*) FROM `alias` WHERE (`domain`= `d`.`domain` OR `domain` IN (SELECT `alias_domain` FROM `alias_domain` WHERE `target_domain` = `d`.`domain`)) AND `address` NOT IN (SELECT `username` FROM `mailbox`)"], ++ ['db' => 'mailboxes', 'dt' => 4, 'order_subquery' => "SELECT COUNT(*) FROM `mailbox` WHERE `mailbox`.`domain` = `d`.`domain` AND (`mailbox`.`kind` = '' OR `mailbox`.`kind` = NULL)"], ++ ['db' => 'quota', 'dt' => 5, 'order_subquery' => "SELECT COALESCE(SUM(`mailbox`.`quota`), 0) FROM `mailbox` WHERE `mailbox`.`domain` = `d`.`domain` AND (`mailbox`.`kind` = '' OR `mailbox`.`kind` = NULL)"], ++ ['db' => 'stats', 'dt' => 6, 'dummy' => true, 'order_subquery' => "SELECT SUM(bytes) FROM `quota2` WHERE `quota2`.`username` IN (SELECT `username` FROM `mailbox` WHERE `domain` = `d`.`domain`)"], ++ ['db' => 'defquota', 'dt' => 7], ++ ['db' => 'maxquota', 'dt' => 8], ++ ['db' => 'backupmx', 'dt' => 10], ++ ['db' => 'tags', 'dt' => 14, 'dummy' => true, 'search' => ['join' => 'LEFT JOIN `tags_domain` AS `td` ON `td`.`domain` = `d`.`domain`', 'where_column' => '`td`.`tag_name`']], ++ ['db' => 'active', 'dt' => 15], ++ ]; ++ ++ if($_SESSION['mailcow_cc_role'] === 'admin') { ++ $data = SSP::simple($requestDecoded, $pdo, $table, $primaryKey, $columns); ++ } elseif ($_SESSION['mailcow_cc_role'] === 'domainadmin') { ++ $data = SSP::complex($requestDecoded, $pdo, $table, $primaryKey, $columns, ++ 'INNER JOIN domain_admins as da ON da.domain = d.domain', ++ [ ++ 'condition' => 'da.active = 1 and da.username = :username', ++ 'bindings' => ['username' => $_SESSION['mailcow_cc_username']] ++ ]); ++ } else { ++ http_response_code(403); ++ echo json_encode(array( ++ 'type' => 'error', ++ 'msg' => 'Insufficient permissions' ++ )); ++ exit(); ++ } ++ ++ if (!empty($data['data'])) { ++ $domainsData = []; ++ foreach ($data['data'] as $domain) { ++ if ($details = mailbox('get', 'domain_details', $domain[2])) { ++ $domainsData[] = $details; ++ } ++ } ++ $data['data'] = $domainsData; ++ } ++ ++ process_search_return($data); ++ break; ++ ++ case "mailbox": ++ $table = ['mailbox', 'm']; ++ $primaryKey = 'username'; ++ $columns = [ ++ ['db' => 'username', 'dt' => 2], ++ ['db' => 'quota', 'dt' => 3], ++ ['db' => 'last_mail_login', 'dt' => 4, 'dummy' => true, 'order_subquery' => "SELECT MAX(`datetime`) FROM `sasl_log` WHERE `service` != 'SSO' AND `username` = `m`.`username`"], ++ ['db' => 'last_pw_change', 'dt' => 5, 'dummy' => true, 'order_subquery' => "JSON_EXTRACT(attributes, '$.passwd_update')"], ++ ['db' => 'in_use', 'dt' => 6, 'dummy' => true, 'order_subquery' => "(SELECT SUM(bytes) FROM `quota2` WHERE `quota2`.`username` = `m`.`username`) / `m`.`quota`"], ++ ['db' => 'name', 'dt' => 7], ++ ['db' => 'messages', 'dt' => 20, 'dummy' => true, 'order_subquery' => "SELECT SUM(messages) FROM `quota2` WHERE `quota2`.`username` = `m`.`username`"], ++ ['db' => 'tags', 'dt' => 23, 'dummy' => true, 'search' => ['join' => 'LEFT JOIN `tags_mailbox` AS `tm` ON `tm`.`username` = `m`.`username`', 'where_column' => '`tm`.`tag_name`']], ++ ['db' => 'active', 'dt' => 24], ++ ]; ++ ++ if($_SESSION['mailcow_cc_role'] === 'admin') { ++ $data = SSP::complex($requestDecoded, $pdo, $table, $primaryKey, $columns, null, ++ "(`m`.`kind` = '' OR `m`.`kind` = NULL)"); ++ } elseif ($_SESSION['mailcow_cc_role'] === 'domainadmin') { ++ $data = SSP::complex($requestDecoded, $pdo, $table, $primaryKey, $columns, ++ 'INNER JOIN domain_admins as da ON da.domain = m.domain', ++ [ ++ 'condition' => "(`m`.`kind` = '' OR `m`.`kind` = NULL) AND `da`.`active` = 1 AND `da`.`username` = :username", ++ 'bindings' => ['username' => $_SESSION['mailcow_cc_username']] ++ ]); ++ } else { ++ http_response_code(403); ++ echo json_encode(array( ++ 'type' => 'error', ++ 'msg' => 'Insufficient permissions' ++ )); ++ exit(); ++ } ++ ++ if (!empty($data['data'])) { ++ $mailboxData = []; ++ foreach ($data['data'] as $mailbox) { ++ if ($details = mailbox('get', 'mailbox_details', $mailbox[2])) { ++ $mailboxData[] = $details; ++ } ++ } ++ $data['data'] = $mailboxData; ++ } ++ ++ process_search_return($data); ++ break; ++ ++ default: ++ http_response_code(404); ++ echo json_encode(array( ++ 'type' => 'error', ++ 'msg' => 'Invalid search category' ++ )); ++ break; ++ } ++ break; + case "delete": + if ($_SESSION['mailcow_cc_api_access'] == 'ro' || isset($_SESSION['pending_mailcow_cc_username']) || !isset($_SESSION["mailcow_cc_username"])) { + http_response_code(403); diff --git a/tasks/mailcow__mailcow-dockerized-7089/solution/solve.sh b/tasks/mailcow__mailcow-dockerized-7089/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7089/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/mailcow__mailcow-dockerized-7089/task.toml b/tasks/mailcow__mailcow-dockerized-7089/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..849fff881f8ff47c1a024f1810b1cbf2c4553d5e --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7089/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/mailcow__mailcow-dockerized-7089" +description = "[Web] switch from GET to POST for datatable requests" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "mailcow-dockerized", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "mailcow/mailcow-dockerized" +ref = "bccfcefd1773e491ac99a9d44649b6d59ee97055" +reference = "https://github.com/mailcow/mailcow-dockerized/pull/7089" +source_access = "auto" +built_at = "2026-11-16T16:09:53.239795+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:d5b48f901ccf038144831b9fe68fff31e31355d84f25b1be812209bdc2049687" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-03-03T14:07:17Z" +diff_format = "unified" +context_files = [ + "data/web/inc/sessions.inc.php", + "data/web/js/site/mailbox.js", + "data/web/json_api.php", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 269 +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.440213+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:818e24ea3293894e390d0bec7a91fdccc75050d55d62ab9daf3e9b4f97c8369e" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/mailcow__mailcow-dockerized-7089/tests/capture.py b/tasks/mailcow__mailcow-dockerized-7089/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7089/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/mailcow__mailcow-dockerized-7089/tests/instruction.md b/tasks/mailcow__mailcow-dockerized-7089/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..908184ab3da86da218dc632a9987421036c8ba60 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7089/tests/instruction.md @@ -0,0 +1,36 @@ +# Issue + +**Title:** [Web] switch from GET to POST for datatable requests + +## Description + + + +## Contribution Guidelines + +* [x] I've read the [contribution guidelines](https://github.com/mailcow/mailcow-dockerized/blob/master/CONTRIBUTING.md) and wholeheartedly agree them + + + +## What does this PR include? + +### Short Description + +This PR switches Datatable search requests from GET to POST method to prevent URI length limitation errors . GET requests can hit URL length limits when searching with complex queries or large datasets, resulting in failed searches or truncated results. + +Fixes: +- + +### Affected Containers + +- None + +## Did you run tests? + +### What did you tested? + +- Datatable search functionality across all admin pages (mailboxes, domains, aliases, etc.) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `bccfcefd1773`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/mailcow__mailcow-dockerized-7089/tests/oracle.patch b/tasks/mailcow__mailcow-dockerized-7089/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..bac5930284c7ca950c0c7ef3c86cb5f3578fba49 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7089/tests/oracle.patch @@ -0,0 +1,331 @@ +diff --git a/data/web/inc/sessions.inc.php b/data/web/inc/sessions.inc.php +index 8f3192d7..ac308b68 100644 +--- a/data/web/inc/sessions.inc.php ++++ b/data/web/inc/sessions.inc.php +@@ -140,17 +140,32 @@ function session_check() { + ); + return false; + } +- if (!empty($_POST)) { +- if ($_SESSION['CSRF']['TOKEN'] != $_POST['csrf_token']) { +- $_SESSION['return'][] = array( +- 'type' => 'warning', +- 'msg' => 'session_token' +- ); +- return false; ++ // Check if this is a POST request (form-encoded or JSON) ++ $is_post_request = !empty($_POST) || ( ++ isset($_SERVER['CONTENT_TYPE']) && ++ strpos($_SERVER['CONTENT_TYPE'], 'application/json') !== false ++ ); ++ ++ if ($is_post_request) { ++ // Skip CSRF check for DataTables server-side processing endpoints ++ // These are read-only operations (equivalent to GET) authenticated by session ++ $is_search_endpoint = ( ++ isset($_GET['query']) && ++ preg_match('#^search/(domain|mailbox)$#', $_GET['query']) ++ ); ++ ++ if (!$is_search_endpoint && !empty($_POST)) { ++ if ($_SESSION['CSRF']['TOKEN'] != $_POST['csrf_token']) { ++ $_SESSION['return'][] = array( ++ 'type' => 'warning', ++ 'msg' => 'session_token' ++ ); ++ return false; ++ } ++ unset($_POST['csrf_token']); ++ $_SESSION['CSRF']['TOKEN'] = bin2hex(random_bytes(32)); ++ $_SESSION['CSRF']['TIME'] = time(); + } +- unset($_POST['csrf_token']); +- $_SESSION['CSRF']['TOKEN'] = bin2hex(random_bytes(32)); +- $_SESSION['CSRF']['TIME'] = time(); + } + return true; + } +diff --git a/data/web/js/site/mailbox.js b/data/web/js/site/mailbox.js +index 7010077d..e8edb994 100644 +--- a/data/web/js/site/mailbox.js ++++ b/data/web/js/site/mailbox.js +@@ -471,8 +471,13 @@ jQuery(function($){ + hideTableExpandCollapseBtn('#tab-domains', '#domain_table'); + }, + ajax: { +- type: "GET", +- url: "/api/v1/get/domain/datatables", ++ type: "POST", ++ url: "/api/v1/search/domain", ++ contentType: "application/json", ++ processData: false, ++ data: function(d) { ++ return JSON.stringify(d); ++ }, + dataSrc: function(json){ + $.each(json.data, function(i, item) { + item.domain_name = escapeHtml(item.domain_name); +@@ -898,8 +903,13 @@ jQuery(function($){ + hideTableExpandCollapseBtn('#tab-mailboxes', '#mailbox_table'); + }, + ajax: { +- type: "GET", +- url: "/api/v1/get/mailbox/datatables", ++ type: "POST", ++ url: "/api/v1/search/mailbox", ++ contentType: "application/json", ++ processData: false, ++ data: function(d) { ++ return JSON.stringify(d); ++ }, + dataSrc: function(json){ + $.each(json.data, function (i, item) { + item.quota = { +diff --git a/data/web/json_api.php b/data/web/json_api.php +index 5409e65d..41f1d265 100644 +--- a/data/web/json_api.php ++++ b/data/web/json_api.php +@@ -91,6 +91,11 @@ if (isset($_GET['query'])) { + if ($action == 'delete') { + $_POST['items'] = $request; + } ++ ++ // search ++ if ($action == 'search') { ++ // placeholder for search, as the request body is already decoded and available in $requestDecoded ++ } + } + api_log($_POST); + +@@ -457,47 +462,6 @@ if (isset($_GET['query'])) { + + case "domain": + switch ($object) { +- case "datatables": +- $table = ['domain', 'd']; +- $primaryKey = 'domain'; +- $columns = [ +- ['db' => 'domain', 'dt' => 2], +- ['db' => 'aliases', 'dt' => 3, 'order_subquery' => "SELECT COUNT(*) FROM `alias` WHERE (`domain`= `d`.`domain` OR `domain` IN (SELECT `alias_domain` FROM `alias_domain` WHERE `target_domain` = `d`.`domain`)) AND `address` NOT IN (SELECT `username` FROM `mailbox`)"], +- ['db' => 'mailboxes', 'dt' => 4, 'order_subquery' => "SELECT COUNT(*) FROM `mailbox` WHERE `mailbox`.`domain` = `d`.`domain` AND (`mailbox`.`kind` = '' OR `mailbox`.`kind` = NULL)"], +- ['db' => 'quota', 'dt' => 5, 'order_subquery' => "SELECT COALESCE(SUM(`mailbox`.`quota`), 0) FROM `mailbox` WHERE `mailbox`.`domain` = `d`.`domain` AND (`mailbox`.`kind` = '' OR `mailbox`.`kind` = NULL)"], +- ['db' => 'stats', 'dt' => 6, 'dummy' => true, 'order_subquery' => "SELECT SUM(bytes) FROM `quota2` WHERE `quota2`.`username` IN (SELECT `username` FROM `mailbox` WHERE `domain` = `d`.`domain`)"], +- ['db' => 'defquota', 'dt' => 7], +- ['db' => 'maxquota', 'dt' => 8], +- ['db' => 'backupmx', 'dt' => 10], +- ['db' => 'tags', 'dt' => 14, 'dummy' => true, 'search' => ['join' => 'LEFT JOIN `tags_domain` AS `td` ON `td`.`domain` = `d`.`domain`', 'where_column' => '`td`.`tag_name`']], +- ['db' => 'active', 'dt' => 15], +- ]; +- +- require_once $_SERVER['DOCUMENT_ROOT'] . '/inc/lib/ssp.class.php'; +- global $pdo; +- if($_SESSION['mailcow_cc_role'] === 'admin') { +- $data = SSP::simple($_GET, $pdo, $table, $primaryKey, $columns); +- } elseif ($_SESSION['mailcow_cc_role'] === 'domainadmin') { +- $data = SSP::complex($_GET, $pdo, $table, $primaryKey, $columns, +- 'INNER JOIN domain_admins as da ON da.domain = d.domain', +- [ +- 'condition' => 'da.active = 1 and da.username = :username', +- 'bindings' => ['username' => $_SESSION['mailcow_cc_username']] +- ]); +- } +- +- if (!empty($data['data'])) { +- $domainsData = []; +- foreach ($data['data'] as $domain) { +- if ($details = mailbox('get', 'domain_details', $domain[2])) { +- $domainsData[] = $details; +- } +- } +- $data['data'] = $domainsData; +- } +- +- process_get_return($data); +- break; + case "all": + $tags = null; + if (isset($_GET['tags']) && $_GET['tags'] != '') +@@ -997,46 +961,6 @@ if (isset($_GET['query'])) { + break; + case "mailbox": + switch ($object) { +- case "datatables": +- $table = ['mailbox', 'm']; +- $primaryKey = 'username'; +- $columns = [ +- ['db' => 'username', 'dt' => 2], +- ['db' => 'quota', 'dt' => 3], +- ['db' => 'last_mail_login', 'dt' => 4, 'dummy' => true, 'order_subquery' => "SELECT MAX(`datetime`) FROM `sasl_log` WHERE `service` != 'SSO' AND `username` = `m`.`username`"], +- ['db' => 'last_pw_change', 'dt' => 5, 'dummy' => true, 'order_subquery' => "JSON_EXTRACT(attributes, '$.passwd_update')"], +- ['db' => 'in_use', 'dt' => 6, 'dummy' => true, 'order_subquery' => "(SELECT SUM(bytes) FROM `quota2` WHERE `quota2`.`username` = `m`.`username`) / `m`.`quota`"], +- ['db' => 'name', 'dt' => 7], +- ['db' => 'messages', 'dt' => 20, 'dummy' => true, 'order_subquery' => "SELECT SUM(messages) FROM `quota2` WHERE `quota2`.`username` = `m`.`username`"], +- ['db' => 'tags', 'dt' => 23, 'dummy' => true, 'search' => ['join' => 'LEFT JOIN `tags_mailbox` AS `tm` ON `tm`.`username` = `m`.`username`', 'where_column' => '`tm`.`tag_name`']], +- ['db' => 'active', 'dt' => 24], +- ]; +- +- require_once $_SERVER['DOCUMENT_ROOT'] . '/inc/lib/ssp.class.php'; +- global $pdo; +- if($_SESSION['mailcow_cc_role'] === 'admin') { +- $data = SSP::complex($_GET, $pdo, $table, $primaryKey, $columns, null, "(`m`.`kind` = '' OR `m`.`kind` = NULL)"); +- } elseif ($_SESSION['mailcow_cc_role'] === 'domainadmin') { +- $data = SSP::complex($_GET, $pdo, $table, $primaryKey, $columns, +- 'INNER JOIN domain_admins as da ON da.domain = m.domain', +- [ +- 'condition' => "(`m`.`kind` = '' OR `m`.`kind` = NULL) AND `da`.`active` = 1 AND `da`.`username` = :username", +- 'bindings' => ['username' => $_SESSION['mailcow_cc_username']] +- ]); +- } +- +- if (!empty($data['data'])) { +- $mailboxData = []; +- foreach ($data['data'] as $mailbox) { +- if ($details = mailbox('get', 'mailbox_details', $mailbox[2])) { +- $mailboxData[] = $details; +- } +- } +- $data['data'] = $mailboxData; +- } +- +- process_get_return($data); +- break; + case "all": + case "reduced": + $tags = null; +@@ -1625,6 +1549,136 @@ if (isset($_GET['query'])) { + } + } + break; ++ case "search": ++ function process_search_return($return) { ++ if ($return === false) { ++ echo json_encode(array( ++ 'type' => 'error', ++ 'msg' => 'Cannot get item' ++ )); ++ } ++ else { ++ echo json_encode($return, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT); ++ } ++ } ++ // only allow POST requests to SEARCH API endpoints ++ if ($_SERVER['REQUEST_METHOD'] != 'POST') { ++ http_response_code(405); ++ echo json_encode(array( ++ 'type' => 'error', ++ 'msg' => 'only POST method is allowed' ++ )); ++ exit(); ++ } ++ ++ // Load SSP class ++ require_once $_SERVER['DOCUMENT_ROOT'] . '/inc/lib/ssp.class.php'; ++ global $pdo; ++ ++ switch ($category) { ++ case "domain": ++ $table = ['domain', 'd']; ++ $primaryKey = 'domain'; ++ $columns = [ ++ ['db' => 'domain', 'dt' => 2], ++ ['db' => 'aliases', 'dt' => 3, 'order_subquery' => "SELECT COUNT(*) FROM `alias` WHERE (`domain`= `d`.`domain` OR `domain` IN (SELECT `alias_domain` FROM `alias_domain` WHERE `target_domain` = `d`.`domain`)) AND `address` NOT IN (SELECT `username` FROM `mailbox`)"], ++ ['db' => 'mailboxes', 'dt' => 4, 'order_subquery' => "SELECT COUNT(*) FROM `mailbox` WHERE `mailbox`.`domain` = `d`.`domain` AND (`mailbox`.`kind` = '' OR `mailbox`.`kind` = NULL)"], ++ ['db' => 'quota', 'dt' => 5, 'order_subquery' => "SELECT COALESCE(SUM(`mailbox`.`quota`), 0) FROM `mailbox` WHERE `mailbox`.`domain` = `d`.`domain` AND (`mailbox`.`kind` = '' OR `mailbox`.`kind` = NULL)"], ++ ['db' => 'stats', 'dt' => 6, 'dummy' => true, 'order_subquery' => "SELECT SUM(bytes) FROM `quota2` WHERE `quota2`.`username` IN (SELECT `username` FROM `mailbox` WHERE `domain` = `d`.`domain`)"], ++ ['db' => 'defquota', 'dt' => 7], ++ ['db' => 'maxquota', 'dt' => 8], ++ ['db' => 'backupmx', 'dt' => 10], ++ ['db' => 'tags', 'dt' => 14, 'dummy' => true, 'search' => ['join' => 'LEFT JOIN `tags_domain` AS `td` ON `td`.`domain` = `d`.`domain`', 'where_column' => '`td`.`tag_name`']], ++ ['db' => 'active', 'dt' => 15], ++ ]; ++ ++ if($_SESSION['mailcow_cc_role'] === 'admin') { ++ $data = SSP::simple($requestDecoded, $pdo, $table, $primaryKey, $columns); ++ } elseif ($_SESSION['mailcow_cc_role'] === 'domainadmin') { ++ $data = SSP::complex($requestDecoded, $pdo, $table, $primaryKey, $columns, ++ 'INNER JOIN domain_admins as da ON da.domain = d.domain', ++ [ ++ 'condition' => 'da.active = 1 and da.username = :username', ++ 'bindings' => ['username' => $_SESSION['mailcow_cc_username']] ++ ]); ++ } else { ++ http_response_code(403); ++ echo json_encode(array( ++ 'type' => 'error', ++ 'msg' => 'Insufficient permissions' ++ )); ++ exit(); ++ } ++ ++ if (!empty($data['data'])) { ++ $domainsData = []; ++ foreach ($data['data'] as $domain) { ++ if ($details = mailbox('get', 'domain_details', $domain[2])) { ++ $domainsData[] = $details; ++ } ++ } ++ $data['data'] = $domainsData; ++ } ++ ++ process_search_return($data); ++ break; ++ ++ case "mailbox": ++ $table = ['mailbox', 'm']; ++ $primaryKey = 'username'; ++ $columns = [ ++ ['db' => 'username', 'dt' => 2], ++ ['db' => 'quota', 'dt' => 3], ++ ['db' => 'last_mail_login', 'dt' => 4, 'dummy' => true, 'order_subquery' => "SELECT MAX(`datetime`) FROM `sasl_log` WHERE `service` != 'SSO' AND `username` = `m`.`username`"], ++ ['db' => 'last_pw_change', 'dt' => 5, 'dummy' => true, 'order_subquery' => "JSON_EXTRACT(attributes, '$.passwd_update')"], ++ ['db' => 'in_use', 'dt' => 6, 'dummy' => true, 'order_subquery' => "(SELECT SUM(bytes) FROM `quota2` WHERE `quota2`.`username` = `m`.`username`) / `m`.`quota`"], ++ ['db' => 'name', 'dt' => 7], ++ ['db' => 'messages', 'dt' => 20, 'dummy' => true, 'order_subquery' => "SELECT SUM(messages) FROM `quota2` WHERE `quota2`.`username` = `m`.`username`"], ++ ['db' => 'tags', 'dt' => 23, 'dummy' => true, 'search' => ['join' => 'LEFT JOIN `tags_mailbox` AS `tm` ON `tm`.`username` = `m`.`username`', 'where_column' => '`tm`.`tag_name`']], ++ ['db' => 'active', 'dt' => 24], ++ ]; ++ ++ if($_SESSION['mailcow_cc_role'] === 'admin') { ++ $data = SSP::complex($requestDecoded, $pdo, $table, $primaryKey, $columns, null, ++ "(`m`.`kind` = '' OR `m`.`kind` = NULL)"); ++ } elseif ($_SESSION['mailcow_cc_role'] === 'domainadmin') { ++ $data = SSP::complex($requestDecoded, $pdo, $table, $primaryKey, $columns, ++ 'INNER JOIN domain_admins as da ON da.domain = m.domain', ++ [ ++ 'condition' => "(`m`.`kind` = '' OR `m`.`kind` = NULL) AND `da`.`active` = 1 AND `da`.`username` = :username", ++ 'bindings' => ['username' => $_SESSION['mailcow_cc_username']] ++ ]); ++ } else { ++ http_response_code(403); ++ echo json_encode(array( ++ 'type' => 'error', ++ 'msg' => 'Insufficient permissions' ++ )); ++ exit(); ++ } ++ ++ if (!empty($data['data'])) { ++ $mailboxData = []; ++ foreach ($data['data'] as $mailbox) { ++ if ($details = mailbox('get', 'mailbox_details', $mailbox[2])) { ++ $mailboxData[] = $details; ++ } ++ } ++ $data['data'] = $mailboxData; ++ } ++ ++ process_search_return($data); ++ break; ++ ++ default: ++ http_response_code(404); ++ echo json_encode(array( ++ 'type' => 'error', ++ 'msg' => 'Invalid search category' ++ )); ++ break; ++ } ++ break; + case "delete": + if ($_SESSION['mailcow_cc_api_access'] == 'ro' || isset($_SESSION['pending_mailcow_cc_username']) || !isset($_SESSION["mailcow_cc_username"])) { + http_response_code(403); diff --git a/tasks/mailcow__mailcow-dockerized-7089/tests/test.sh b/tasks/mailcow__mailcow-dockerized-7089/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..55401cbbc2356558737599cabb65575d0a1374e7 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7089/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace bccfcefd1773e491ac99a9d44649b6d59ee97055 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/mailcow__mailcow-dockerized-7089/tests/verifier.py b/tasks/mailcow__mailcow-dockerized-7089/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7089/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/mailcow__mailcow-dockerized-7091/environment/Dockerfile b/tasks/mailcow__mailcow-dockerized-7091/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..1ff3f976903f23626950079893f1805b7dd03fe3 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7091/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/mailcow/mailcow-dockerized.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/mailcow/mailcow-dockerized.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/mailcow/mailcow-dockerized.git +WORKDIR /workspace +RUN git fetch --depth 1 origin ddc2309f1e03da1e7228db3a0cbf8cc6207a2b71 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard ddc2309f1e03da1e7228db3a0cbf8cc6207a2b71 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base ddc2309f1e03da1e7228db3a0cbf8cc6207a2b71 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/mailcow__mailcow-dockerized-7091/instruction.md b/tasks/mailcow__mailcow-dockerized-7091/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f4a24257841f1b69ab58769956e09eb42c7450a6 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7091/instruction.md @@ -0,0 +1,15 @@ +# Issue + +**Title:** Translations update from Weblate + +## Description + +Translations update from [Weblate](https://translate.mailcow.email) for [mailcow: dockerized - 🐮 + 🐋 = 💕/Translation](https://translate.mailcow.email/projects/mailcow-dockerized/translation/). + +Current translation status: + +![Weblate translation status](https://translate.mailcow.email/widget/mailcow-dockerized/translation/horizontal-auto.svg) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `ddc2309f1e03`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/mailcow__mailcow-dockerized-7091/solution/patch.diff b/tasks/mailcow__mailcow-dockerized-7091/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..301dc80ed6028ee99d029a59d0f9240b146776b1 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7091/solution/patch.diff @@ -0,0 +1,61 @@ +diff --git a/data/web/lang/lang.de-de.json b/data/web/lang/lang.de-de.json +index 06137344..487300fe 100644 +--- a/data/web/lang/lang.de-de.json ++++ b/data/web/lang/lang.de-de.json +@@ -686,8 +686,6 @@ + "extended_sender_acl_info": "Der DKIM-Domainkey der externen Absenderdomain sollte in diesen Server importiert werden, falls vorhanden.
    \r\n Wird SPF verwendet, muss diesem Server der Versand gestattet werden.
    \r\n Wird eine Domain oder Alias-Domain zu diesem Server hinzugefügt, die sich mit der externen Absenderadresse überschneidet, wird der externe Absender hier entfernt.
    \r\n Ein Eintrag @domain.tld erlaubt den Versand als *@domain.tld", + "force_pw_update": "Erzwinge Passwortänderung bei nächstem Login", + "force_pw_update_info": "Dem Benutzer wird lediglich der Zugang zur %s ermöglicht, App Passwörter funktionieren weiterhin.", +- "force_tfa": "Zwei-Faktor-Authentifizierung beim Login erzwingen", +- "force_tfa_info": "Der Benutzer muss Zwei-Faktor-Authentifizierung einrichten, bevor er auf den Bereich zugreifen kann.", + "footer_exclude": "von Fußzeile ausschließen", + "full_name": "Voller Name", + "gal": "Globales Adressbuch", +@@ -1241,8 +1239,7 @@ + "force_tfa_info": "Der Benutzer muss Zwei-Faktor-Authentifizierung einrichten, bevor er auf den Bereich zugreifen kann.", + "setup_title": "Zwei-Faktor-Authentifizierung erforderlich", + "setup_required": "Ihr Konto erfordert Zwei-Faktor-Authentifizierung. Bitte richten Sie eine 2FA-Methode ein, um fortzufahren.", +- "cancel_setup": "Abbrechen und abmelden", +- "disable_tfa_blocked": "Die Zwei-Faktor-Authentifizierung kann nicht deaktiviert werden, da sie für dieses Konto erforderlich ist." ++ "cancel_setup": "Abbrechen und abmelden" + }, + "user": { + "action": "Aktion", +diff --git a/data/web/lang/lang.si-si.json b/data/web/lang/lang.si-si.json +index 4c8177a0..5b7b8574 100644 +--- a/data/web/lang/lang.si-si.json ++++ b/data/web/lang/lang.si-si.json +@@ -557,7 +557,8 @@ + "max_age_invalid": "Najvišja starost %s je neveljavna", + "mode_invalid": "Način %s ni veljaven", + "mx_invalid": "Zapis MX %s je neveljaven", +- "version_invalid": "Različica %s je neveljavna" ++ "version_invalid": "Različica %s je neveljavna", ++ "tfa_removal_blocked": "Dvofaktorske avtentikacije ni mogoče odstraniti, ker je obvezna za vaš račun." + }, + "debug": { + "containers_info": "Informacije o zabojniku", +@@ -1232,7 +1233,12 @@ + "u2f_deprecated_important": "Prosimo, registrirajte svoj ključ v skrbniški plošči z novo metodo WebAuthn.", + "waiting_usb_auth": "Čakanje na napravo USB ...

    Zdaj se dotaknite gumba na napravi USB.", + "waiting_usb_register": "Čakanje na napravo USB ...

    Vnesite svoje geslo zgoraj in potrdite registracijo tako, da tapnete gumb na napravi USB.", +- "yubi_otp": "Avtentikacija z enkratnim geslom Yubico" ++ "yubi_otp": "Avtentikacija z enkratnim geslom Yubico", ++ "force_tfa": "Vsiljena registracija 2FA ob prijavi", ++ "force_tfa_info": "Uporabnik bo moral pred dostopom do nadzorne plošče nastaviti dvofaktorsko overjanje.", ++ "setup_title": "Zahtevana je dvofaktorska avtentikacija", ++ "setup_required": "Vaš račun zahteva dvofaktorsko overjanje. Za nadaljevanje nastavite metodo dvofaktorske overitve.", ++ "cancel_setup": "Prekliči in se odjavi" + }, + "ratelimit": { + "disabled": "Onemogočeno", +@@ -1413,7 +1419,8 @@ + "syncjob_EX_OK": "Uspeh", + "expire_never": "Nikoli ne poteče", + "forever": "Za vedno", +- "spam_aliases_info": "Vzdevek za neželeno pošto je začasni e-poštni naslov, ki ga je mogoče uporabiti za zaščito pravih e-poštnih naslovov.
    Po želji je mogoče nastaviti čas poteka veljavnosti, tako da se vzdevek po določenem obdobju samodejno deaktivira, s čimer se učinkovito znebite zlorabljenih ali razkritih naslovov." ++ "spam_aliases_info": "Vzdevek za neželeno pošto je začasni e-poštni naslov, ki ga je mogoče uporabiti za zaščito pravih e-poštnih naslovov.
    Po želji je mogoče nastaviti čas poteka veljavnosti, tako da se vzdevek po določenem obdobju samodejno deaktivira, s čimer se učinkovito znebite zlorabljenih ali razkritih naslovov.", ++ "pw_update_required": "Za vaš račun je potrebna sprememba gesla. Za nadaljevanje nastavite novo geslo." + }, + "warning": { + "cannot_delete_self": "Prijavljenega uporabnika ni mogoče izbrisati", diff --git a/tasks/mailcow__mailcow-dockerized-7091/solution/solve.sh b/tasks/mailcow__mailcow-dockerized-7091/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7091/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/mailcow__mailcow-dockerized-7091/task.toml b/tasks/mailcow__mailcow-dockerized-7091/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..49b190bb7a660a1904b5891a1393a8bdbb44ebb9 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7091/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/mailcow__mailcow-dockerized-7091" +description = "Translations update from Weblate" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "mailcow-dockerized", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "mailcow/mailcow-dockerized" +ref = "ddc2309f1e03da1e7228db3a0cbf8cc6207a2b71" +reference = "https://github.com/mailcow/mailcow-dockerized/pull/7091" +source_access = "auto" +built_at = "2026-11-16T16:09:53.236175+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:a16601ad8f6a656190d1edd03d925d890933ead76d6f99777b50814caef96ffa" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-03-03T19:25:24Z" +diff_format = "unified" +context_files = [ + "data/web/lang/lang.de-de.json", + "data/web/lang/lang.si-si.json", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 18 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.440674+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:e8509e950412d84031afd54221bd059818efbc9fd051306a83a607453025be3e" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/mailcow__mailcow-dockerized-7091/tests/capture.py b/tasks/mailcow__mailcow-dockerized-7091/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7091/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/mailcow__mailcow-dockerized-7091/tests/instruction.md b/tasks/mailcow__mailcow-dockerized-7091/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f4a24257841f1b69ab58769956e09eb42c7450a6 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7091/tests/instruction.md @@ -0,0 +1,15 @@ +# Issue + +**Title:** Translations update from Weblate + +## Description + +Translations update from [Weblate](https://translate.mailcow.email) for [mailcow: dockerized - 🐮 + 🐋 = 💕/Translation](https://translate.mailcow.email/projects/mailcow-dockerized/translation/). + +Current translation status: + +![Weblate translation status](https://translate.mailcow.email/widget/mailcow-dockerized/translation/horizontal-auto.svg) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `ddc2309f1e03`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/mailcow__mailcow-dockerized-7091/tests/oracle.patch b/tasks/mailcow__mailcow-dockerized-7091/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..301dc80ed6028ee99d029a59d0f9240b146776b1 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7091/tests/oracle.patch @@ -0,0 +1,61 @@ +diff --git a/data/web/lang/lang.de-de.json b/data/web/lang/lang.de-de.json +index 06137344..487300fe 100644 +--- a/data/web/lang/lang.de-de.json ++++ b/data/web/lang/lang.de-de.json +@@ -686,8 +686,6 @@ + "extended_sender_acl_info": "Der DKIM-Domainkey der externen Absenderdomain sollte in diesen Server importiert werden, falls vorhanden.
    \r\n Wird SPF verwendet, muss diesem Server der Versand gestattet werden.
    \r\n Wird eine Domain oder Alias-Domain zu diesem Server hinzugefügt, die sich mit der externen Absenderadresse überschneidet, wird der externe Absender hier entfernt.
    \r\n Ein Eintrag @domain.tld erlaubt den Versand als *@domain.tld", + "force_pw_update": "Erzwinge Passwortänderung bei nächstem Login", + "force_pw_update_info": "Dem Benutzer wird lediglich der Zugang zur %s ermöglicht, App Passwörter funktionieren weiterhin.", +- "force_tfa": "Zwei-Faktor-Authentifizierung beim Login erzwingen", +- "force_tfa_info": "Der Benutzer muss Zwei-Faktor-Authentifizierung einrichten, bevor er auf den Bereich zugreifen kann.", + "footer_exclude": "von Fußzeile ausschließen", + "full_name": "Voller Name", + "gal": "Globales Adressbuch", +@@ -1241,8 +1239,7 @@ + "force_tfa_info": "Der Benutzer muss Zwei-Faktor-Authentifizierung einrichten, bevor er auf den Bereich zugreifen kann.", + "setup_title": "Zwei-Faktor-Authentifizierung erforderlich", + "setup_required": "Ihr Konto erfordert Zwei-Faktor-Authentifizierung. Bitte richten Sie eine 2FA-Methode ein, um fortzufahren.", +- "cancel_setup": "Abbrechen und abmelden", +- "disable_tfa_blocked": "Die Zwei-Faktor-Authentifizierung kann nicht deaktiviert werden, da sie für dieses Konto erforderlich ist." ++ "cancel_setup": "Abbrechen und abmelden" + }, + "user": { + "action": "Aktion", +diff --git a/data/web/lang/lang.si-si.json b/data/web/lang/lang.si-si.json +index 4c8177a0..5b7b8574 100644 +--- a/data/web/lang/lang.si-si.json ++++ b/data/web/lang/lang.si-si.json +@@ -557,7 +557,8 @@ + "max_age_invalid": "Najvišja starost %s je neveljavna", + "mode_invalid": "Način %s ni veljaven", + "mx_invalid": "Zapis MX %s je neveljaven", +- "version_invalid": "Različica %s je neveljavna" ++ "version_invalid": "Različica %s je neveljavna", ++ "tfa_removal_blocked": "Dvofaktorske avtentikacije ni mogoče odstraniti, ker je obvezna za vaš račun." + }, + "debug": { + "containers_info": "Informacije o zabojniku", +@@ -1232,7 +1233,12 @@ + "u2f_deprecated_important": "Prosimo, registrirajte svoj ključ v skrbniški plošči z novo metodo WebAuthn.", + "waiting_usb_auth": "Čakanje na napravo USB ...

    Zdaj se dotaknite gumba na napravi USB.", + "waiting_usb_register": "Čakanje na napravo USB ...

    Vnesite svoje geslo zgoraj in potrdite registracijo tako, da tapnete gumb na napravi USB.", +- "yubi_otp": "Avtentikacija z enkratnim geslom Yubico" ++ "yubi_otp": "Avtentikacija z enkratnim geslom Yubico", ++ "force_tfa": "Vsiljena registracija 2FA ob prijavi", ++ "force_tfa_info": "Uporabnik bo moral pred dostopom do nadzorne plošče nastaviti dvofaktorsko overjanje.", ++ "setup_title": "Zahtevana je dvofaktorska avtentikacija", ++ "setup_required": "Vaš račun zahteva dvofaktorsko overjanje. Za nadaljevanje nastavite metodo dvofaktorske overitve.", ++ "cancel_setup": "Prekliči in se odjavi" + }, + "ratelimit": { + "disabled": "Onemogočeno", +@@ -1413,7 +1419,8 @@ + "syncjob_EX_OK": "Uspeh", + "expire_never": "Nikoli ne poteče", + "forever": "Za vedno", +- "spam_aliases_info": "Vzdevek za neželeno pošto je začasni e-poštni naslov, ki ga je mogoče uporabiti za zaščito pravih e-poštnih naslovov.
    Po želji je mogoče nastaviti čas poteka veljavnosti, tako da se vzdevek po določenem obdobju samodejno deaktivira, s čimer se učinkovito znebite zlorabljenih ali razkritih naslovov." ++ "spam_aliases_info": "Vzdevek za neželeno pošto je začasni e-poštni naslov, ki ga je mogoče uporabiti za zaščito pravih e-poštnih naslovov.
    Po želji je mogoče nastaviti čas poteka veljavnosti, tako da se vzdevek po določenem obdobju samodejno deaktivira, s čimer se učinkovito znebite zlorabljenih ali razkritih naslovov.", ++ "pw_update_required": "Za vaš račun je potrebna sprememba gesla. Za nadaljevanje nastavite novo geslo." + }, + "warning": { + "cannot_delete_self": "Prijavljenega uporabnika ni mogoče izbrisati", diff --git a/tasks/mailcow__mailcow-dockerized-7091/tests/test.sh b/tasks/mailcow__mailcow-dockerized-7091/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..8392bb421b09d38cd336c4434d795c9687785ec5 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7091/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace ddc2309f1e03da1e7228db3a0cbf8cc6207a2b71 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/mailcow__mailcow-dockerized-7091/tests/verifier.py b/tasks/mailcow__mailcow-dockerized-7091/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7091/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/mailcow__mailcow-dockerized-7093/environment/Dockerfile b/tasks/mailcow__mailcow-dockerized-7093/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2bf9c6275f87e3b2e610238c1768fcf98a55302b --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7093/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/mailcow/mailcow-dockerized.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/mailcow/mailcow-dockerized.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/mailcow/mailcow-dockerized.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4c184b25f45b6784a52577dbac871b2a6fafe6cb 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4c184b25f45b6784a52577dbac871b2a6fafe6cb \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4c184b25f45b6784a52577dbac871b2a6fafe6cb \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/mailcow__mailcow-dockerized-7093/instruction.md b/tasks/mailcow__mailcow-dockerized-7093/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..046804ad6bab8c0b4097fdd73898d5f6154fec2f --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7093/instruction.md @@ -0,0 +1,34 @@ +# Issue + +**Title:** [SOGo][Web] use incremental updates for mailbox/alias/resource sync in sogo_static_view + +## Description + +## Contribution Guidelines + +* [x] I've read the [contribution guidelines](https://github.com/mailcow/mailcow-dockerized/blob/master/CONTRIBUTING.md) and wholeheartedly agree them + +## What does this PR include? + +### Short Description + +This PR optimizes SOGo synchronization by implementing incremental updates for mailbox, alias, and resource operations instead of triggering expensive full rebuilds of the `_sogo_static_view` table. + +**Problem**: Previously, adding/editing/deleting a single alias or resource would trigger a full rebuild of the SOGo static view for ALL mailboxes + +Fixes: +- + +### Affected Containers + +- phpfpm-mailcow + +## Did you run tests? + +### What did you tested? + +Tested add/edit/delete operations for mailboxes, aliases, and resources. Verified that all changes are correctly reflected in SOGo. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4c184b25f45b`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/mailcow__mailcow-dockerized-7093/solution/patch.diff b/tasks/mailcow__mailcow-dockerized-7093/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..114a48a0d395cab8f71ee1fea1ff46d87c188897 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7093/solution/patch.diff @@ -0,0 +1,195 @@ +diff --git a/data/web/inc/functions.mailbox.inc.php b/data/web/inc/functions.mailbox.inc.php +index e8f3eb3d..a002ab41 100644 +--- a/data/web/inc/functions.mailbox.inc.php ++++ b/data/web/inc/functions.mailbox.inc.php +@@ -9,6 +9,10 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { + $_data_log = $_data; + !isset($_data_log['password']) ?: $_data_log['password'] = '*'; + !isset($_data_log['password2']) ?: $_data_log['password2'] = '*'; ++ ++ // Track mailboxes affected by alias operations for incremental SOGo updates ++ $update_sogo_mailboxes = array(); ++ + switch ($_action) { + case 'add': + switch ($_type) { +@@ -886,6 +890,17 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { + 'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr), + 'msg' => array('alias_added', $address, $id) + ); ++ ++ // Track affected mailboxes for SOGo update ++ if (!empty($goto)) { ++ $gotos = array_map('trim', explode(',', $goto)); ++ foreach ($gotos as $g) { ++ if (filter_var($g, FILTER_VALIDATE_EMAIL) && ++ !in_array($g, array('null@localhost', 'spam@localhost', 'ham@localhost'))) { ++ $update_sogo_mailboxes[] = $g; ++ } ++ } ++ } + } + break; + case 'alias_domain': +@@ -1368,15 +1383,8 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { + ), $_extra); + } + +- try { +- update_sogo_static_view($username); +- } catch (PDOException $e) { +- $_SESSION['return'][] = array( +- 'type' => 'danger', +- 'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr), +- 'msg' => $e->getMessage() +- ); +- } ++ // Track affected mailboxes for SOGo update ++ $update_sogo_mailboxes[] = $username; + $_SESSION['return'][] = array( + 'type' => 'success', + 'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr), +@@ -1607,6 +1615,9 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { + 'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr), + 'msg' => array('resource_added', htmlspecialchars($name)) + ); ++ ++ // Track affected mailboxes for SOGo update ++ $update_sogo_mailboxes[] = $name; + break; + case 'domain_templates': + if ($_SESSION['mailcow_cc_role'] != "admin") { +@@ -2725,6 +2736,28 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { + 'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr), + 'msg' => array('alias_modified', htmlspecialchars($address)) + ); ++ ++ // Track affected mailboxes for SOGo update (both old and new goto addresses) ++ // Old goto: to remove alias from their view ++ if (!empty($is_now['goto'])) { ++ $old_gotos = array_map('trim', explode(',', $is_now['goto'])); ++ foreach ($old_gotos as $g) { ++ if (filter_var($g, FILTER_VALIDATE_EMAIL) && ++ !in_array($g, array('null@localhost', 'spam@localhost', 'ham@localhost'))) { ++ $update_sogo_mailboxes[] = $g; ++ } ++ } ++ } ++ // New goto: to add alias to their view ++ if (!empty($goto)) { ++ $new_gotos = array_map('trim', explode(',', $goto)); ++ foreach ($new_gotos as $g) { ++ if (filter_var($g, FILTER_VALIDATE_EMAIL) && ++ !in_array($g, array('null@localhost', 'spam@localhost', 'ham@localhost'))) { ++ $update_sogo_mailboxes[] = $g; ++ } ++ } ++ } + } + break; + case 'domain': +@@ -3439,15 +3472,8 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { + 'msg' => array('mailbox_modified', $username) + ); + +- try { +- update_sogo_static_view($username); +- } catch (PDOException $e) { +- $_SESSION['return'][] = array( +- 'type' => 'danger', +- 'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr), +- 'msg' => $e->getMessage() +- ); +- } ++ // Track affected mailboxes for SOGo update ++ $update_sogo_mailboxes[] = $username; + } + return true; + break; +@@ -4076,6 +4102,9 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { + 'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr), + 'msg' => array('resource_modified', htmlspecialchars($name)) + ); ++ ++ // Track affected mailboxes for SOGo update ++ $update_sogo_mailboxes[] = $name; + } + break; + case 'domain_wide_footer': +@@ -5780,6 +5809,18 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { + ); + continue; + } ++ ++ // Track affected mailboxes for SOGo update (capture before deletion) ++ if (!empty($alias_data['goto'])) { ++ $gotos = array_map('trim', explode(',', $alias_data['goto'])); ++ foreach ($gotos as $g) { ++ if (filter_var($g, FILTER_VALIDATE_EMAIL) && ++ !in_array($g, array('null@localhost', 'spam@localhost', 'ham@localhost'))) { ++ $update_sogo_mailboxes[] = $g; ++ } ++ } ++ } ++ + $stmt = $pdo->prepare("DELETE FROM `alias` WHERE `id` = :id"); + $stmt->execute(array( + ':id' => $alias_data['id'] +@@ -6038,20 +6079,14 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { + continue; + } + +- try { +- update_sogo_static_view($username); +- }catch (PDOException $e) { +- $_SESSION['return'][] = array( +- 'type' => 'success', +- 'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr), +- 'msg' => $e->getMessage() +- ); +- } + $_SESSION['return'][] = array( + 'type' => 'success', + 'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr), + 'msg' => array('mailbox_removed', htmlspecialchars($username)) + ); ++ ++ // Track affected mailboxes for SOGo update ++ $update_sogo_mailboxes[] = $username; + } + return true; + break; +@@ -6153,6 +6188,9 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { + 'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr), + 'msg' => array('resource_removed', htmlspecialchars($name)) + ); ++ ++ // Track affected mailboxes for SOGo update ++ $update_sogo_mailboxes[] = $name; + } + break; + case 'tags_domain': +@@ -6259,9 +6297,21 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { + } + break; + } +- if ($_action != 'get' && in_array($_type, array('domain', 'alias', 'alias_domain', 'resource')) && getenv('SKIP_SOGO') != "y") { ++ if ($_action != 'get' && in_array($_type, array('domain', 'alias', 'alias_domain', 'resource', 'mailbox')) && getenv('SKIP_SOGO') != "y") { + try { +- update_sogo_static_view(); ++ if (($_type == 'alias' || $_type == 'resource' || $_type == 'mailbox') && !empty($update_sogo_mailboxes)) { ++ // INCREMENTAL UPDATE: Update only affected mailboxes/resources ++ $update_sogo_mailboxes = array_unique($update_sogo_mailboxes); ++ foreach ($update_sogo_mailboxes as $mailbox) { ++ update_sogo_static_view($mailbox); ++ } ++ } ++ else { ++ // FULL REBUILD: For domain and alias_domain operations or if no tracked mailboxes ++ // Domain operations affect all mailboxes ++ // Alias_domain operations affect entire target domain ++ update_sogo_static_view(); ++ } + }catch (PDOException $e) { + $_SESSION['return'][] = array( + 'type' => 'success', diff --git a/tasks/mailcow__mailcow-dockerized-7093/solution/solve.sh b/tasks/mailcow__mailcow-dockerized-7093/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7093/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/mailcow__mailcow-dockerized-7093/task.toml b/tasks/mailcow__mailcow-dockerized-7093/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..c67d15ea842234773abf3ebec059aeaca97e5825 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7093/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/mailcow__mailcow-dockerized-7093" +description = "[SOGo][Web] use incremental updates for mailbox/alias/resource sync in sogo_static_view" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "mailcow-dockerized", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "mailcow/mailcow-dockerized" +ref = "4c184b25f45b6784a52577dbac871b2a6fafe6cb" +reference = "https://github.com/mailcow/mailcow-dockerized/pull/7093" +source_access = "auto" +built_at = "2026-11-16T16:09:53.218195+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:fbfa36386b1faa0376c9516390a936b570fd1fdb192821e6f77f4ac0443809a1" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-03-06T08:23:00Z" +diff_format = "unified" +context_files = [ + "data/web/inc/functions.mailbox.inc.php", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 108 +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.441131+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:4a2771911cec1e8e0e65cf892c848f6e4e6378cad8f806b2a8618b6a44bfe0e8" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/mailcow__mailcow-dockerized-7093/tests/capture.py b/tasks/mailcow__mailcow-dockerized-7093/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7093/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/mailcow__mailcow-dockerized-7093/tests/instruction.md b/tasks/mailcow__mailcow-dockerized-7093/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..046804ad6bab8c0b4097fdd73898d5f6154fec2f --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7093/tests/instruction.md @@ -0,0 +1,34 @@ +# Issue + +**Title:** [SOGo][Web] use incremental updates for mailbox/alias/resource sync in sogo_static_view + +## Description + +## Contribution Guidelines + +* [x] I've read the [contribution guidelines](https://github.com/mailcow/mailcow-dockerized/blob/master/CONTRIBUTING.md) and wholeheartedly agree them + +## What does this PR include? + +### Short Description + +This PR optimizes SOGo synchronization by implementing incremental updates for mailbox, alias, and resource operations instead of triggering expensive full rebuilds of the `_sogo_static_view` table. + +**Problem**: Previously, adding/editing/deleting a single alias or resource would trigger a full rebuild of the SOGo static view for ALL mailboxes + +Fixes: +- + +### Affected Containers + +- phpfpm-mailcow + +## Did you run tests? + +### What did you tested? + +Tested add/edit/delete operations for mailboxes, aliases, and resources. Verified that all changes are correctly reflected in SOGo. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4c184b25f45b`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/mailcow__mailcow-dockerized-7093/tests/oracle.patch b/tasks/mailcow__mailcow-dockerized-7093/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..114a48a0d395cab8f71ee1fea1ff46d87c188897 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7093/tests/oracle.patch @@ -0,0 +1,195 @@ +diff --git a/data/web/inc/functions.mailbox.inc.php b/data/web/inc/functions.mailbox.inc.php +index e8f3eb3d..a002ab41 100644 +--- a/data/web/inc/functions.mailbox.inc.php ++++ b/data/web/inc/functions.mailbox.inc.php +@@ -9,6 +9,10 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { + $_data_log = $_data; + !isset($_data_log['password']) ?: $_data_log['password'] = '*'; + !isset($_data_log['password2']) ?: $_data_log['password2'] = '*'; ++ ++ // Track mailboxes affected by alias operations for incremental SOGo updates ++ $update_sogo_mailboxes = array(); ++ + switch ($_action) { + case 'add': + switch ($_type) { +@@ -886,6 +890,17 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { + 'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr), + 'msg' => array('alias_added', $address, $id) + ); ++ ++ // Track affected mailboxes for SOGo update ++ if (!empty($goto)) { ++ $gotos = array_map('trim', explode(',', $goto)); ++ foreach ($gotos as $g) { ++ if (filter_var($g, FILTER_VALIDATE_EMAIL) && ++ !in_array($g, array('null@localhost', 'spam@localhost', 'ham@localhost'))) { ++ $update_sogo_mailboxes[] = $g; ++ } ++ } ++ } + } + break; + case 'alias_domain': +@@ -1368,15 +1383,8 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { + ), $_extra); + } + +- try { +- update_sogo_static_view($username); +- } catch (PDOException $e) { +- $_SESSION['return'][] = array( +- 'type' => 'danger', +- 'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr), +- 'msg' => $e->getMessage() +- ); +- } ++ // Track affected mailboxes for SOGo update ++ $update_sogo_mailboxes[] = $username; + $_SESSION['return'][] = array( + 'type' => 'success', + 'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr), +@@ -1607,6 +1615,9 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { + 'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr), + 'msg' => array('resource_added', htmlspecialchars($name)) + ); ++ ++ // Track affected mailboxes for SOGo update ++ $update_sogo_mailboxes[] = $name; + break; + case 'domain_templates': + if ($_SESSION['mailcow_cc_role'] != "admin") { +@@ -2725,6 +2736,28 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { + 'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr), + 'msg' => array('alias_modified', htmlspecialchars($address)) + ); ++ ++ // Track affected mailboxes for SOGo update (both old and new goto addresses) ++ // Old goto: to remove alias from their view ++ if (!empty($is_now['goto'])) { ++ $old_gotos = array_map('trim', explode(',', $is_now['goto'])); ++ foreach ($old_gotos as $g) { ++ if (filter_var($g, FILTER_VALIDATE_EMAIL) && ++ !in_array($g, array('null@localhost', 'spam@localhost', 'ham@localhost'))) { ++ $update_sogo_mailboxes[] = $g; ++ } ++ } ++ } ++ // New goto: to add alias to their view ++ if (!empty($goto)) { ++ $new_gotos = array_map('trim', explode(',', $goto)); ++ foreach ($new_gotos as $g) { ++ if (filter_var($g, FILTER_VALIDATE_EMAIL) && ++ !in_array($g, array('null@localhost', 'spam@localhost', 'ham@localhost'))) { ++ $update_sogo_mailboxes[] = $g; ++ } ++ } ++ } + } + break; + case 'domain': +@@ -3439,15 +3472,8 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { + 'msg' => array('mailbox_modified', $username) + ); + +- try { +- update_sogo_static_view($username); +- } catch (PDOException $e) { +- $_SESSION['return'][] = array( +- 'type' => 'danger', +- 'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr), +- 'msg' => $e->getMessage() +- ); +- } ++ // Track affected mailboxes for SOGo update ++ $update_sogo_mailboxes[] = $username; + } + return true; + break; +@@ -4076,6 +4102,9 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { + 'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr), + 'msg' => array('resource_modified', htmlspecialchars($name)) + ); ++ ++ // Track affected mailboxes for SOGo update ++ $update_sogo_mailboxes[] = $name; + } + break; + case 'domain_wide_footer': +@@ -5780,6 +5809,18 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { + ); + continue; + } ++ ++ // Track affected mailboxes for SOGo update (capture before deletion) ++ if (!empty($alias_data['goto'])) { ++ $gotos = array_map('trim', explode(',', $alias_data['goto'])); ++ foreach ($gotos as $g) { ++ if (filter_var($g, FILTER_VALIDATE_EMAIL) && ++ !in_array($g, array('null@localhost', 'spam@localhost', 'ham@localhost'))) { ++ $update_sogo_mailboxes[] = $g; ++ } ++ } ++ } ++ + $stmt = $pdo->prepare("DELETE FROM `alias` WHERE `id` = :id"); + $stmt->execute(array( + ':id' => $alias_data['id'] +@@ -6038,20 +6079,14 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { + continue; + } + +- try { +- update_sogo_static_view($username); +- }catch (PDOException $e) { +- $_SESSION['return'][] = array( +- 'type' => 'success', +- 'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr), +- 'msg' => $e->getMessage() +- ); +- } + $_SESSION['return'][] = array( + 'type' => 'success', + 'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr), + 'msg' => array('mailbox_removed', htmlspecialchars($username)) + ); ++ ++ // Track affected mailboxes for SOGo update ++ $update_sogo_mailboxes[] = $username; + } + return true; + break; +@@ -6153,6 +6188,9 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { + 'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr), + 'msg' => array('resource_removed', htmlspecialchars($name)) + ); ++ ++ // Track affected mailboxes for SOGo update ++ $update_sogo_mailboxes[] = $name; + } + break; + case 'tags_domain': +@@ -6259,9 +6297,21 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { + } + break; + } +- if ($_action != 'get' && in_array($_type, array('domain', 'alias', 'alias_domain', 'resource')) && getenv('SKIP_SOGO') != "y") { ++ if ($_action != 'get' && in_array($_type, array('domain', 'alias', 'alias_domain', 'resource', 'mailbox')) && getenv('SKIP_SOGO') != "y") { + try { +- update_sogo_static_view(); ++ if (($_type == 'alias' || $_type == 'resource' || $_type == 'mailbox') && !empty($update_sogo_mailboxes)) { ++ // INCREMENTAL UPDATE: Update only affected mailboxes/resources ++ $update_sogo_mailboxes = array_unique($update_sogo_mailboxes); ++ foreach ($update_sogo_mailboxes as $mailbox) { ++ update_sogo_static_view($mailbox); ++ } ++ } ++ else { ++ // FULL REBUILD: For domain and alias_domain operations or if no tracked mailboxes ++ // Domain operations affect all mailboxes ++ // Alias_domain operations affect entire target domain ++ update_sogo_static_view(); ++ } + }catch (PDOException $e) { + $_SESSION['return'][] = array( + 'type' => 'success', diff --git a/tasks/mailcow__mailcow-dockerized-7093/tests/test.sh b/tasks/mailcow__mailcow-dockerized-7093/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..732d540934180c000bc6bd2567391c7a822c4c27 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7093/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 4c184b25f45b6784a52577dbac871b2a6fafe6cb > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/mailcow__mailcow-dockerized-7093/tests/verifier.py b/tasks/mailcow__mailcow-dockerized-7093/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7093/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/mailcow__mailcow-dockerized-7095/environment/Dockerfile b/tasks/mailcow__mailcow-dockerized-7095/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..eda907c7caf970ee52deead1e1318465a9a6c963 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7095/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/mailcow/mailcow-dockerized.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/mailcow/mailcow-dockerized.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/mailcow/mailcow-dockerized.git +WORKDIR /workspace +RUN git fetch --depth 1 origin fe71f84c822c69104c61ac8f6bc9c6f299366d76 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard fe71f84c822c69104c61ac8f6bc9c6f299366d76 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base fe71f84c822c69104c61ac8f6bc9c6f299366d76 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/mailcow__mailcow-dockerized-7095/instruction.md b/tasks/mailcow__mailcow-dockerized-7095/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b7af7a218a43eac53eaf9f8807e0c3293c6e6cef --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7095/instruction.md @@ -0,0 +1,15 @@ +# Issue + +**Title:** Translations update from Weblate + +## Description + +Translations update from [Weblate](https://translate.mailcow.email) for [mailcow: dockerized - 🐮 + 🐋 = 💕/Translation](https://translate.mailcow.email/projects/mailcow-dockerized/translation/). + +Current translation status: + +![Weblate translation status](https://translate.mailcow.email/widget/mailcow-dockerized/translation/horizontal-auto.svg) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `fe71f84c822c`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/mailcow__mailcow-dockerized-7095/solution/patch.diff b/tasks/mailcow__mailcow-dockerized-7095/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..a9e32bf7790150492c342bd9cd1e723dbe0734a7 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7095/solution/patch.diff @@ -0,0 +1,378 @@ +diff --git a/data/web/lang/lang.nl-nl.json b/data/web/lang/lang.nl-nl.json +index 71ec9720..7b341cec 100644 +--- a/data/web/lang/lang.nl-nl.json ++++ b/data/web/lang/lang.nl-nl.json +@@ -26,7 +26,8 @@ + "syncjobs": "Sync jobs", + "tls_policy": "Versleutelingsbeleid", + "unlimited_quota": "Onbeperkte quota voor mailboxen", +- "domain_desc": "Wijzig domeinbeschrijving" ++ "domain_desc": "Wijzig domeinbeschrijving", ++ "pw_reset": "Toegang om mailcow gebruikers wachtwoord te resetten" + }, + "add": { + "activate_filter_warn": "Alle andere filters worden gedeactiveerd zolang deze geactiveerd is.", +@@ -104,7 +105,11 @@ + "validate": "Verifieer", + "validation_success": "Succesvol geverifieerd", + "tags": "Tags", +- "bcc_dest_format": "BCC-bestemming moet één geldig e-mailadres zijn.
    Als u een kopie naar meerdere adressen wilt sturen, maak dan een alias aan en gebruik die hier." ++ "bcc_dest_format": "BCC-bestemming moet één geldig e-mailadres zijn.
    Als u een kopie naar meerdere adressen wilt sturen, maak dan een alias aan en gebruik die hier.", ++ "dry": "Synchronisatie simuleren", ++ "internal": "Intern", ++ "internal_info": "Interne aliassen zijn alleen toegankelijk vanuit het eigen (alias)domein.", ++ "sender_allowed": "Toestaan om te verzenden als deze alias" + }, + "admin": { + "access": "Toegang", +@@ -138,7 +143,7 @@ + "arrival_time": "Aankomsttijd", + "authed_user": "Geauthenticeerde gebruiker", + "ays": "Weet je zeker dat je deze actie wilt uitvoeren?", +- "ban_list_info": "Bekijk de lijst met verbannen IP-adressen hieronder: netwerk (resterende tijd) - [acties].
    Rode labels geven een permanente verbanning aan.
    Het kan enkele seconden duren voordat wijzigingen hieronder zichtbaar zijn.", ++ "ban_list_info": "Bekijk de lijst met verbannen IP-adressen hieronder: netwerk (resterende tijd) - [acties].
    IP-adressen die in de wachtrij staan om te worden gedeblokkeerd, worden binnen enkele seconden uit de actieve banlijst verwijderd.
    \n
    Rode labels geven actieve permanente blokkades door denylisting aan.", + "change_logo": "Logo", + "configuration": "Instellingen", + "convert_html_to_text": "Converteer HTML naar plaintext", +@@ -171,7 +176,7 @@ + "excludes": "Exclusief", + "f2b_ban_time": "Verbanningstijd (s)", + "f2b_ban_time_increment": "Verbanningstijd wordt verhoogd met elk verbanning", +- "f2b_blacklist": "Netwerken/hosts op de blacklist", ++ "f2b_blacklist": "Netwerken/hosts op de denylist", + "f2b_filter": "Regex-filters", + "f2b_list_info": "Een host of netwerk op de blacklist staat altijd boven eenzelfde op de whitelist. Het doorvoeren van wijzigingen kan enkele seconden in beslag nemen.", + "f2b_max_attempts": "Maximaal aantal pogingen", +@@ -206,7 +211,7 @@ + "link": "Link", + "loading": "Even geduld aub...", + "logo_info": "De afbeelding zal worden geschaald naar een hoogte van 40px voor de navigatiebar, en naar een breedte van 250px voor de startpagina.", +- "lookup_mx": "Match bestemming aan MX (gebruik .outlook.com om alle mail gericht aan MX *.outlook.com over deze hop te laten gaan)", ++ "lookup_mx": "Bestemming is een reguliere expressie die wordt gematcht met de MX-naam (.*\\.google\\.com om alle e-mail die gericht is aan een MX die eindigt op google.com via deze hop te routeren)", + "main_name": "\"Mailcow\"", + "merged_vars_hint": "Grijze rijen zijn samengevoegd van vars.(local.)inc.php en kunnen niet worden gewijzigd.", + "message": "Bericht", +@@ -275,7 +280,7 @@ + "rspamd_com_settings": "Een beschrijving voor deze instelling zal automatisch worden gegenereerd, gebruik de onderstaande presets als voorbeeld. Raadpleeg de Rspamd-documentatie voor meer informatie.", + "rspamd_global_filters": "Globale filters", + "rspamd_global_filters_agree": "Ik ben me ervan bewust dat aanpassingen desastreuze gevolgen kunnen hebben", +- "rspamd_global_filters_info": "Ieder globaal filter heeft zijn eigen functie, zie de namen.", ++ "rspamd_global_filters_info": "Globale filtermaps bevatten verschillende soorten globale deny- en allowlists.", + "rspamd_global_filters_regex": "De velden kunnen uitsluitend regular expressions bevatten met het formaat \"/pattern/options\", bijvoorbeeld /.+@domain\\.tld/i.
    Ondanks dat alle invoer wordt gecontroleerd op fouten, is het toch mogelijk dat Rspamd onbruikbaar wordt als deze de invoer niet kan lezen.
    Als je problemen ervaart, herstart Rspamd dan om de filters opnieuw te laten lezen.
    Elementen op de blacklist zijn uitgesloten van de quarantaine.", + "rspamd_settings_map": "Rspamd", + "sal_level": "Moo-level", +@@ -337,7 +342,71 @@ + "admins_ldap": "LDAP administrators", + "api_read_only": "Alleen-lezen toegang", + "api_read_write": "Lees en schrijf toegang", +- "login_time": "Login tijd" ++ "login_time": "Login tijd", ++ "admin_quicklink": "Snelle link naar de admin-loginpagina verbergen", ++ "allowed_methods": "Toegestane toegangsmethoden", ++ "app_hide": "Verberg voor login", ++ "copy_to_clipboard": "Tekst gekopieerd naar het klembord!", ++ "login_page": "Loginpagina", ++ "domainadmin_quicklink": "Snelle link naar de domeinbeheerder-loginpagina verbergen", ++ "f2b_manage_external": "Fail2Ban extern beheren", ++ "f2b_manage_external_info": "Fail2Ban zal nog steeds de banlijst bijhouden, maar zal niet actief regels instellen om verkeer te blokkeren. Gebruik de onderstaande gegenereerde banlijst om het verkeer extern te blokkeren.", ++ "filter": "Filter", ++ "force_sso_text": "Als een externe OIDC-provider is geconfigureerd, verbergt deze optie de standaard Mailcow-loginformulieren en wordt alleen de Single SignOn-knop weergegeven.", ++ "force_sso": "Mailcow-login uitschakelen en alleen Single SignOn tonen", ++ "iam": "Identiteitsprovider", ++ "iam_attribute_field": "Attribuutveld", ++ "iam_authorize_url": "Autorisatie endpoint", ++ "iam_auth_flow": "Autorisatie flow", ++ "iam_auth_flow_info": "Naast de Authorization Code Flow (Standard Flow in Keycloak), die wordt gebruikt voor Single SignOn-login, ondersteunt Mailcow ook een authenticatiestroom met directe inloggegevens. De Mailpassword Flow probeert de gebruikersgegevens te valideren door gebruik te maken van de Keycloak Admin REST API. Mailcow haalt het gehashte wachtwoord op uit het attribuut mailcow_password, dat in Keycloak is gekoppeld.", ++ "iam_client_id": "Client ID", ++ "iam_client_secret": "Client Secret", ++ "iam_client_scopes": "Clientscopes", ++ "iam_default_template": "Standaardsjabloon", ++ "iam_default_template_description": "Als er geen sjabloon aan een gebruiker is toegewezen, wordt het standaardsjabloon gebruikt voor het aanmaken van de mailbox, maar niet voor het bijwerken van de mailbox.", ++ "iam_description": "Configureer een externe provider voor authenticatie. De mailboxen van gebruikers worden automatisch aangemaakt bij hun eerste login, mits er een attribuutkoppeling is ingesteld.", ++ "iam_extra_permission": "Om de volgende instellingen te laten werken, heeft de mailcow-client in Keycloak een service account nodig en de toestemming view-users.", ++ "iam_host": "Hostname", ++ "iam_host_info": "Voer één of meerdere LDAP-hosts in, gescheiden door komma’s.", ++ "iam_import_users": "Importeer gebruikers", ++ "iam_login_provisioning": "Gebruikers automatisch aanmaken bij het inloggen", ++ "iam_mapping": "Attribuutkoppeling", ++ "iam_bindpass": "Bind-wachtwoord", ++ "iam_periodic_full_sync": "Periodieke volledige synchronisatie", ++ "iam_port": "Poort", ++ "iam_realm": "Realm", ++ "iam_redirect_url": "Redirect-URL", ++ "iam_rest_flow": "Mailwachtwoord-flow", ++ "iam_server_url": "Server Url", ++ "iam_sso": "Single SignOn", ++ "iam_sync_interval": "Synchronisatie-/importinterval (min)", ++ "iam_test_connection": "Verbinding testen", ++ "iam_token_url": "Token endpoint", ++ "iam_userinfo_url": "Gebruikersinfo endpoint", ++ "iam_username_field": "Gebruikersnaam veld", ++ "iam_use_ssl": "Gebruik SSL", ++ "iam_use_ssl_info": "Als SSL wordt ingeschakeld en de poort is ingesteld op 389, wordt deze automatisch aangepast naar 636.", ++ "iam_use_tls": "Gebruik StartTLS", ++ "iam_use_tls_info": "Als TLS wordt ingeschakeld, moet je de standaardpoort voor je LDAP-server (389) gebruiken. SSL-poorten kunnen niet worden gebruikt.", ++ "iam_version": "Versie", ++ "ignore_ssl_error": "Negeer SSL foutmeldingen", ++ "ip_check_opt_in": "Kies ervoor om de externe diensten ipv4.mailcow.email en ipv6.mailcow.email te gebruiken om externe IP-adressen te bepalen.", ++ "needs_restart": "vereist een herstart", ++ "no": "✕", ++ "password_reset_info": "Als er geen herstel-e-mailadres is opgegeven, kan deze functie niet worden gebruikt.", ++ "password_reset_settings": "Instellingen voor wachtwoordherstel", ++ "password_reset_tmpl_html": "HTML sjabloon", ++ "password_reset_tmpl_text": "Tekst sjabloon", ++ "password_settings": "Wachtwoordinstellingen", ++ "quicklink_text": "Toon of verberg snelle links naar andere inlogpagina’s onder het inlogformulier", ++ "queue_unban": "deblokkeren", ++ "reset_password_vars": "{{link}} De gegenereerde link om het wachtwoord te resetten
    {{username}} De mailboxnaam van de gebruiker die het wachtwoordherstel heeft aangevraagd
    {{username2}} De naam van de herstelmailbox
    {{date}} De datum waarop het verzoek tot wachtwoordherstel is gedaan
    {{token_lifetime}} De geldigheidsduur van de token in minuten
    {{hostname}} De mailcow-hostnaam", ++ "restore_template": "Leeg laten om het standaardsjabloon te herstellen.", ++ "task": "Taak", ++ "transport_test_rcpt_info": "• Gebruik null@hosted.mailcow.de om relaying naar een externe bestemming te testen.", ++ "user_link": "Gebruikerslink", ++ "user_quicklink": "Snelle link naar de gebruikers-loginpagina verbergen", ++ "yes": "✓" + }, + "danger": { + "access_denied": "Toegang geweigerd of ongeldige gegevens", +@@ -463,7 +532,27 @@ + "demo_mode_enabled": "Demo modus is ingeschakeld", + "template_exists": "Sjabloon %s bestaat al", + "template_id_invalid": "Sjabloon ID %s ongeldig", +- "template_name_invalid": "Sjabloon naam ongeldig" ++ "template_name_invalid": "Sjabloon naam ongeldig", ++ "tfa_removal_blocked": "Twee-factor-authenticatie kan niet worden verwijderd omdat dit vereist is voor uw account.", ++ "authsource_in_use": "De identiteitsprovider kan niet worden gewijzigd of verwijderd omdat deze momenteel door één of meerdere gebruikers wordt gebruikt.", ++ "cors_invalid_origin": "Ongeldige Allow-Origin opgegeven", ++ "extended_sender_acl_denied": "Ontbrekende ACL om externe afzenderadressen in te stellen", ++ "generic_server_error": "Er is een onverwachte serverfout opgetreden. Neem contact op met uw beheerder.", ++ "iam_test_connection": "Verbinding mislukt", ++ "img_dimensions_exceeded": "De afbeelding overschrijdt de maximale afbeeldingsgrootte", ++ "img_size_exceeded": "De afbeelding overschrijdt de maximale afbeeldingsgrootte", ++ "invalid_reset_token": "Ongeldige reset-token", ++ "max_age_invalid": "Maximale leeftijd %s is ongeldig", ++ "mode_invalid": "Mode %s is ongeldig", ++ "mx_invalid": "MX-record %s is ongeldig", ++ "password_reset_invalid_user": "Mailbox niet gevonden of er is geen herstel-e-mailadres ingesteld", ++ "password_reset_na": "Wachtwoordherstel is momenteel niet beschikbaar. Neem contact op met uw beheerder.", ++ "recovery_email_failed": "Kon geen herstel-e-mail verzenden. Neem contact op met uw beheerder.", ++ "required_data_missing": "Vereiste gegevens %s ontbreken", ++ "reset_token_limit_exceeded": "De limiet voor reset-tokens is overschreden. Probeer het later opnieuw.", ++ "to_invalid": "Ontvanger mag niet leeg zijn", ++ "webauthn_username_failed": "De geselecteerde authenticator behoort tot een ander account", ++ "version_invalid": "Versie %s is ongeldig" + }, + "debug": { + "chart_this_server": "Grafiek (deze server)", +@@ -520,7 +609,7 @@ + "alias": "Wijzig alias", + "allow_from_smtp": "Sta enkel de volgende IP-adressen toe voor SMTP", + "allow_from_smtp_info": "Laat leeg om alle afzenders toe te staan.
    IPv4/IPv6-adressen en netwerken.", +- "allowed_protocols": "Toegestane protocollen", ++ "allowed_protocols": "Toegestane protocollen voor directe gebruikerstoegang (heeft geen invloed op protocollen voor app-wachtwoorden).", + "app_name": "Naam van app", + "app_passwd": "Appwachtwoord", + "automap": "Probeer mappen automatisch te koppelen (\"Verzonden items\", \"Verzonden\" => \"Verzonden\" etc.)", +@@ -605,7 +694,7 @@ + "sogo_visible_info": "Wanneer verborgen zal een alias niet worden weergegeven als een selecteerbaar verzendadres. Deze optie beïnvloedt uitsluitend objecten die kunnen worden weergegeven in SOGo (gedeelde of niet-gedeelde aliasadressen die naar minstens één mailbox verwijzen).", + "spam_alias": "Maak een nieuw tijdelijk alias aan, of pas deze aan", + "spam_filter": "Spamfilter", +- "spam_policy": "Voeg items toe of verwijder items van de white- of blacklist", ++ "spam_policy": "Voeg items toe of verwijder items van de deny- en allowlists", + "spam_score": "Stel een aangepaste spamscore in", + "subfolder2": "Synchroniseer in submap op bestemming
    (leeg = gebruik geen submappen)", + "syncjob": "Wijzig sync job", +@@ -624,7 +713,47 @@ + "acl": "ACL (Toestemming)", + "domain_footer": "Domeinbreede footer", + "domain_footer_html": "HTML footer", +- "mailbox_relayhost_info": "Wordt alleen toegepast op de mailbox en directe aliassen, maar heft een domein relayhost op." ++ "mailbox_relayhost_info": "Wordt alleen toegepast op de mailbox en directe aliassen, maar heft een domein relayhost op.", ++ "custom_attributes": "Aangepaste attributen", ++ "domain_footer_info_vars": { ++ "auth_user": "{= auth_user =} - Geauthenticeerde gebruikersnaam opgegeven door een MTA", ++ "from_user": "{= from_user =} - Afzendergedeelte van het e-mailadres, bijvoorbeeld bij \"moo@mailcow.tld\" wordt \"moo\" teruggegeven", ++ "from_name": "{= from_name =} - Naam van de afzender, bijvoorbeeld bij \"Mailcow \" wordt \"Mailcow\" teruggegeven", ++ "from_addr": "{= from_addr =} - Adres van de afzender", ++ "from_domain": "{= from_domain =} - Domein van de afzender", ++ "custom": "{= foo =} - Als de mailbox het aangepaste attribuut \"foo\" met de waarde \"bar\" heeft, wordt \"bar\" teruggegeven." ++ }, ++ "domain_footer_plain": "PLAIN-voettekst", ++ "domain_footer_skip_replies": "Voettekst negeren bij antwoord-e-mails", ++ "footer_exclude": "Uitsluiten van voettekst", ++ "internal": "Intern", ++ "internal_info": "Interne aliassen zijn alleen toegankelijk vanuit het eigen (alias)domein.", ++ "sender_allowed": "Toestaan om als deze alias te verzenden", ++ "sender_allowed_info": "Als dit is uitgeschakeld, kan deze alias alleen e-mail ontvangen. Gebruik de afzender-ACL om dit te overschrijven en specifieke mailboxen toestemming te geven om te verzenden.", ++ "lookup_mx": "Bestemming is een reguliere expressie die wordt gematcht met de MX-naam (.*.google.com om alle e-mail die gericht is aan een MX die eindigt op google.com via deze hop te routeren)", ++ "mailbox_rename": "Hernoem mailbox", ++ "mailbox_rename_agree": "Ik heb een backup gemaakt.", ++ "mailbox_rename_warning": "BELANGRIJK! Maak een back-up voordat u de mailbox hernoemt.", ++ "mailbox_rename_alias": "Alias automatisch aanmaken.", ++ "mailbox_rename_title": "Nieuwe naam van de lokale mailbox", ++ "mta_sts": "MTA-STS", ++ "mta_sts_info": "MTA-STS is een standaard die afdwingt dat e-mailbezorging tussen mailservers TLS met geldige certificaten gebruikt.
    \nDeze wordt gebruikt wanneer DANE niet mogelijk is vanwege ontbrekende of niet-ondersteunde DNSSEC.
    \nOpmerking: Als het ontvangende domein DANE met DNSSEC ondersteunt, heeft DANE altijd de voorkeur – MTA-STS fungeert alleen als een fallback.", ++ "mta_sts_version": "Versie", ++ "mta_sts_version_info": "Definieert de versie van de MTA-STS-standaard – momenteel is alleen STSv1 geldig.", ++ "mta_sts_mode": "Modus", ++ "mta_sts_mode_info": "Er zijn drie modus om uit te kiezen:
    • testing – het beleid wordt alleen gemonitord, overtredingen hebben geen impact.
    • enforce – het beleid wordt strikt afgedwongen, verbindingen zonder geldige TLS worden geweigerd.
    • none – het beleid wordt gepubliceerd maar niet toegepast.
    ", ++ "mta_sts_max_age": "Maximale leeftijd", ++ "mta_sts_max_age_info": "Tijd in seconden dat ontvangende mailservers dit beleid mogen cachen voordat het opnieuw wordt opgehaald.", ++ "mta_sts_mx": "MX server", ++ "mta_sts_mx_info": "Staat verzending alleen toe naar expliciet vermelde mailserver-hostnamen; de verzendende MTA controleert of de DNS MX-hostnaam overeenkomt met de beleidslijst en staat levering alleen toe met een geldig TLS-certificaat (beschermt tegen MITM).", ++ "mta_sts_mx_notice": "Meerdere MX-servers kunnen worden opgegeven (gescheiden door komma’s).", ++ "none_inherit": "Geen / Erven", ++ "password_recovery_email": "E-mail voor wachtwoordherstel", ++ "pushover": "Pushover", ++ "quota_warning_bcc": "Quotum waarschuwing BCC", ++ "quota_warning_bcc_info": "Waarschuwingen zullen in afzonderlijke exemplaren naar de volgende ontvangers worden gestuurd. Het onderwerp zal worden gevolgd door de bijbehorende gebruikersnaam tussen haakjes, bijvoorbeeld: Contingentwaarschuwing (user@example.com).", ++ "sogo_access": "Verleen directe logintoegang tot SOGo", ++ "sogo_access_info": "Na het inloggen wordt de gebruiker automatisch doorgestuurd naar SOGo" + }, + "footer": { + "cancel": "Annuleren", +@@ -637,18 +766,21 @@ + "restart_container": "Herstart container", + "restart_container_info": "Belangrijk: Een herstart kan enige tijd in beslag nemen, wacht aub totdat dit proces voltooid is.
    Deze pagina zal zichzelf verversen zodra het proces voltooid is.", + "restart_now": "Nu herstarten", +- "restarting_container": "Container wordt herstart, even geduld aub..." ++ "restarting_container": "Container wordt herstart, even geduld aub...", ++ "hibp_check": "Controleer tegen haveibeenpwned.com", ++ "nothing_selected": "Niets geselecteerd" + }, + "header": { + "administration": "Configuratie & details", + "apps": "Apps", +- "debug": "Systeeminformatie", ++ "debug": "Informatie", + "email": "E-Mail", + "mailcow_config": "Beheer", + "quarantine": "Quarantaine", + "restart_netfilter": "Herstart netfilter", + "restart_sogo": "Herstart SOGo", +- "user_settings": "Gebruikersinstellingen" ++ "user_settings": "Gebruikersinstellingen", ++ "mailcow_system": "Systeem" + }, + "info": { + "awaiting_tfa_confirmation": "In afwachting van tweefactorauthenticatie...", +@@ -662,7 +794,22 @@ + "mobileconfig_info": "Log in als mailboxgebruiker om het Apple-verbindingsprofiel te downloaden.", + "other_logins": "of aanmelden met", + "password": "Wachtwoord", +- "username": "Gebruikersnaam" ++ "username": "Gebruikersnaam", ++ "back_to_mailcow": "Terug naar mailcow", ++ "forgot_password": "> Wachtwoord vergeten?", ++ "invalid_pass_reset_token": "De reset-wachtwoordtoken is ongeldig of verlopen.
    Vraag een nieuwe link voor het resetten van het wachtwoord aan.", ++ "login_linkstext": "Niet de juiste login?", ++ "login_usertext": "Log in als gebruiker", ++ "login_domainadmintext": "Login in als domeinbeheerder", ++ "login_admintext": "Log in als administrator", ++ "login_user": "Gebruikerslogin", ++ "login_dadmin": "Domeinbeheerder login", ++ "login_admin": "Administrator login", ++ "new_password": "Nieuw wachtwoord", ++ "new_password_confirm": "Bevestig nieuw wachtwoord", ++ "reset_password": "Herstel wachtwoord", ++ "request_reset_password": "Verzoek wachtwoord wijziging", ++ "email": "E-mailadres" + }, + "mailbox": { + "action": "Handeling", +@@ -782,7 +929,7 @@ + "sieve_preset_5": "Autoreply (vakantie)", + "sieve_preset_6": "Weiger mail met antwoord", + "sieve_preset_7": "Forward en behoud/verwijder", +- "sieve_preset_8": "Verwijder mail verstuurd naar een aliasadres van de afzender", ++ "sieve_preset_8": "E-mail van een specifieke afzender doorsturen, als gelezen markeren en in een submap plaatsen", + "sieve_preset_header": "Zie de onderstaande voorbeelden. Raadpleeg Wikipedia voor meer informatie.", + "sogo_visible": "Alias tonen in SOGo", + "sogo_visible_n": "Verberg alias in SOGo", +@@ -809,7 +956,37 @@ + "toggle_all": "Selecteer alles", + "username": "Gebruikersnaam", + "waiting": "Wachten", +- "weekly": "Wekelijks" ++ "weekly": "Wekelijks", ++ "add_alias_expand": "Alias uitbreiden over alias-domeinen", ++ "add_template": "Sjabloon toevoegen", ++ "all_domains": "Alle domeinen", ++ "catch_all": "Catch-All", ++ "created_on": "Aangemaakt op", ++ "domain_templates": "Domein sjablonen", ++ "domain_quota_total": "Totale domein-opslagruimte", ++ "goto_ham": "Leren als Ham", ++ "goto_spam": "Leren als spam", ++ "iam": "Identiteitsprovider", ++ "internal": "Intern", ++ "last_pw_change": "Laatste wachtwoordwijziging", ++ "mailbox_templates": "Mailbox sjablonen", ++ "no": "✕", ++ "open_logs": "Open logs", ++ "recipient": "Ontvanger", ++ "relay_unknown": "Onbekende mailboxen relayen", ++ "sender": "Afzender", ++ "syncjob_check_log": "Controleer log", ++ "syncjob_last_run_result": "Laatste uitvoeringsresultaat", ++ "syncjob_EX_OK": "Succes", ++ "syncjob_EXIT_CONNECTION_FAILURE": "Verbindingsprobleem", ++ "syncjob_EXIT_TLS_FAILURE": "Probleem met versleutelde verbinding", ++ "syncjob_EXIT_AUTHENTICATION_FAILURE": "Authenticatieprobleem", ++ "syncjob_EXIT_OVERQUOTA": "Doel mailbox is over quota", ++ "syncjob_EXIT_CONNECTION_FAILURE_HOST1": "Kan geen verbinding maken met de externe server", ++ "syncjob_EXIT_AUTHENTICATION_FAILURE_USER1": "Verkeerde gebruikersnaam of wachtwoord", ++ "templates": "Sjablonen", ++ "template": "Sjabloon", ++ "yes": "✓" + }, + "oauth2": { + "access_denied": "Log in als een mailboxgebruiker om toegang via OAuth te verlenen", +@@ -842,7 +1019,7 @@ + "notified": "Verwittigd", + "qhandler_success": "Aanvraag succesvol verzonden naar het systeem. Je kunt nu het venster sluiten.", + "qid": "Rspamd QID", +- "qinfo": "Het quarantainesysteem slaat een kopie van zowel geweigerde mail (voor de afzender zal het lijken alsof de mail niet afgeleverd is), als mail die afgeleverd is de spamfolder, op in de database.\r\n
    \"Markeer als spam en verwijder\" traint het systeem om soortgelijke mails in de toekomst opnieuw als spam te markeren.\r\n
    Wanneer er meerdere berichten tegelijkertijd worden behandeld kan het mogelijk enige tijd duren.
    Elementen op de blacklist zijn uitgesloten van de quarantaine.", ++ "qinfo": "Het quarantainesysteem slaat een kopie van zowel geweigerde mail (voor de afzender zal het lijken alsof de mail niet afgeleverd is), als mail die afgeleverd is de spamfolder, op in de database.\n
    \"Markeer als spam en verwijder\" traint het systeem om soortgelijke mails in de toekomst opnieuw als spam te markeren.\n
    Wanneer er meerdere berichten tegelijkertijd worden behandeld kan het mogelijk enige tijd duren.
    Elementen op de denylist zijn uitgesloten van de quarantaine.", + "qitem": "Quarantaine-item", + "quarantine": "Quarantaine", + "quick_actions": "Handelingen", +@@ -874,7 +1051,19 @@ + "toggle_all": "Selecteer alles" + }, + "queue": { +- "queue_manager": "Queue manager" ++ "queue_manager": "Queue manager", ++ "delete": "Verwijder alles", ++ "flush": "Wachtrij leegmaken", ++ "info": "De mailwachtrij bevat alle e-mails die wachten op aflevering. Als een e-mail lange tijd in de mailwachtrij blijft staan, wordt deze automatisch door het systeem verwijderd.
    De foutmelding van de betreffende e-mail geeft informatie over waarom de e-mail niet kon worden afgeleverd.", ++ "legend": "Functies voor acties in de mailwachtrij:", ++ "ays": "Bevestig dat u alle items uit de huidige wachtrij wilt verwijderen.", ++ "deliver_mail": "Afleveren", ++ "deliver_mail_legend": "Probeert de geselecteerde e-mails opnieuw te bezorgen.", ++ "hold_mail": "Vasthouden", ++ "hold_mail_legend": "Houdt de geselecteerde e-mails vast. (Voorkomt verdere afleverpogingen)", ++ "show_message": "Bericht weergeven", ++ "unban": "Wachtrij deblokkeren", ++ "unhold_mail": "Vrijgeven" + }, + "start": { + "help": "Toon/verberg hulppaneel", +@@ -994,7 +1183,8 @@ + "start_fido2_validation": "Start FIDO2-validatie", + "fido2_auth": "Aanmelden met FIDO2", + "fido2_success": "Apparaat succesvol geregistreerd", +- "fido2_validation_failed": "Validatie mislukt" ++ "fido2_validation_failed": "Validatie mislukt", ++ "set_fido2_touchid": "Registreer Touch ID op Apple M1" + }, + "user": { + "action": "Handeling", +@@ -1161,6 +1351,7 @@ + "loadingRecords": "Laden...", + "processing": "Wachten alstublieft..", + "search": "Zoeken:", +- "zeroRecords": "Geen overeenkomsten gevonden" ++ "zeroRecords": "Geen overeenkomsten gevonden", ++ "infoFiltered": "(gefilterd uit _MAX_ totale vermeldingen)" + } + } diff --git a/tasks/mailcow__mailcow-dockerized-7095/solution/solve.sh b/tasks/mailcow__mailcow-dockerized-7095/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7095/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/mailcow__mailcow-dockerized-7095/task.toml b/tasks/mailcow__mailcow-dockerized-7095/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ebdf106e96c1d4f62997363587230228f6570fa8 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7095/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/mailcow__mailcow-dockerized-7095" +description = "Translations update from Weblate" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "mailcow-dockerized", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "mailcow/mailcow-dockerized" +ref = "fe71f84c822c69104c61ac8f6bc9c6f299366d76" +reference = "https://github.com/mailcow/mailcow-dockerized/pull/7095" +source_access = "auto" +built_at = "2026-11-16T16:09:53.234534+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:1343a33984fac6601244f269bcc373a1cb2e53557fc3720aab3844782aeb11b7" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-03-04T22:03:02Z" +diff_format = "unified" +context_files = [ + "data/web/lang/lang.nl-nl.json", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 233 +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.441621+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:99b85661c72159ad332c47139c963975a7b6cd99a6ce8830e6f29a0d8bf014e8" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/mailcow__mailcow-dockerized-7095/tests/capture.py b/tasks/mailcow__mailcow-dockerized-7095/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7095/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/mailcow__mailcow-dockerized-7095/tests/instruction.md b/tasks/mailcow__mailcow-dockerized-7095/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b7af7a218a43eac53eaf9f8807e0c3293c6e6cef --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7095/tests/instruction.md @@ -0,0 +1,15 @@ +# Issue + +**Title:** Translations update from Weblate + +## Description + +Translations update from [Weblate](https://translate.mailcow.email) for [mailcow: dockerized - 🐮 + 🐋 = 💕/Translation](https://translate.mailcow.email/projects/mailcow-dockerized/translation/). + +Current translation status: + +![Weblate translation status](https://translate.mailcow.email/widget/mailcow-dockerized/translation/horizontal-auto.svg) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `fe71f84c822c`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/mailcow__mailcow-dockerized-7095/tests/oracle.patch b/tasks/mailcow__mailcow-dockerized-7095/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..a9e32bf7790150492c342bd9cd1e723dbe0734a7 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7095/tests/oracle.patch @@ -0,0 +1,378 @@ +diff --git a/data/web/lang/lang.nl-nl.json b/data/web/lang/lang.nl-nl.json +index 71ec9720..7b341cec 100644 +--- a/data/web/lang/lang.nl-nl.json ++++ b/data/web/lang/lang.nl-nl.json +@@ -26,7 +26,8 @@ + "syncjobs": "Sync jobs", + "tls_policy": "Versleutelingsbeleid", + "unlimited_quota": "Onbeperkte quota voor mailboxen", +- "domain_desc": "Wijzig domeinbeschrijving" ++ "domain_desc": "Wijzig domeinbeschrijving", ++ "pw_reset": "Toegang om mailcow gebruikers wachtwoord te resetten" + }, + "add": { + "activate_filter_warn": "Alle andere filters worden gedeactiveerd zolang deze geactiveerd is.", +@@ -104,7 +105,11 @@ + "validate": "Verifieer", + "validation_success": "Succesvol geverifieerd", + "tags": "Tags", +- "bcc_dest_format": "BCC-bestemming moet één geldig e-mailadres zijn.
    Als u een kopie naar meerdere adressen wilt sturen, maak dan een alias aan en gebruik die hier." ++ "bcc_dest_format": "BCC-bestemming moet één geldig e-mailadres zijn.
    Als u een kopie naar meerdere adressen wilt sturen, maak dan een alias aan en gebruik die hier.", ++ "dry": "Synchronisatie simuleren", ++ "internal": "Intern", ++ "internal_info": "Interne aliassen zijn alleen toegankelijk vanuit het eigen (alias)domein.", ++ "sender_allowed": "Toestaan om te verzenden als deze alias" + }, + "admin": { + "access": "Toegang", +@@ -138,7 +143,7 @@ + "arrival_time": "Aankomsttijd", + "authed_user": "Geauthenticeerde gebruiker", + "ays": "Weet je zeker dat je deze actie wilt uitvoeren?", +- "ban_list_info": "Bekijk de lijst met verbannen IP-adressen hieronder: netwerk (resterende tijd) - [acties].
    Rode labels geven een permanente verbanning aan.
    Het kan enkele seconden duren voordat wijzigingen hieronder zichtbaar zijn.", ++ "ban_list_info": "Bekijk de lijst met verbannen IP-adressen hieronder: netwerk (resterende tijd) - [acties].
    IP-adressen die in de wachtrij staan om te worden gedeblokkeerd, worden binnen enkele seconden uit de actieve banlijst verwijderd.
    \n
    Rode labels geven actieve permanente blokkades door denylisting aan.", + "change_logo": "Logo", + "configuration": "Instellingen", + "convert_html_to_text": "Converteer HTML naar plaintext", +@@ -171,7 +176,7 @@ + "excludes": "Exclusief", + "f2b_ban_time": "Verbanningstijd (s)", + "f2b_ban_time_increment": "Verbanningstijd wordt verhoogd met elk verbanning", +- "f2b_blacklist": "Netwerken/hosts op de blacklist", ++ "f2b_blacklist": "Netwerken/hosts op de denylist", + "f2b_filter": "Regex-filters", + "f2b_list_info": "Een host of netwerk op de blacklist staat altijd boven eenzelfde op de whitelist. Het doorvoeren van wijzigingen kan enkele seconden in beslag nemen.", + "f2b_max_attempts": "Maximaal aantal pogingen", +@@ -206,7 +211,7 @@ + "link": "Link", + "loading": "Even geduld aub...", + "logo_info": "De afbeelding zal worden geschaald naar een hoogte van 40px voor de navigatiebar, en naar een breedte van 250px voor de startpagina.", +- "lookup_mx": "Match bestemming aan MX (gebruik .outlook.com om alle mail gericht aan MX *.outlook.com over deze hop te laten gaan)", ++ "lookup_mx": "Bestemming is een reguliere expressie die wordt gematcht met de MX-naam (.*\\.google\\.com om alle e-mail die gericht is aan een MX die eindigt op google.com via deze hop te routeren)", + "main_name": "\"Mailcow\"", + "merged_vars_hint": "Grijze rijen zijn samengevoegd van vars.(local.)inc.php en kunnen niet worden gewijzigd.", + "message": "Bericht", +@@ -275,7 +280,7 @@ + "rspamd_com_settings": "Een beschrijving voor deze instelling zal automatisch worden gegenereerd, gebruik de onderstaande presets als voorbeeld. Raadpleeg de Rspamd-documentatie voor meer informatie.", + "rspamd_global_filters": "Globale filters", + "rspamd_global_filters_agree": "Ik ben me ervan bewust dat aanpassingen desastreuze gevolgen kunnen hebben", +- "rspamd_global_filters_info": "Ieder globaal filter heeft zijn eigen functie, zie de namen.", ++ "rspamd_global_filters_info": "Globale filtermaps bevatten verschillende soorten globale deny- en allowlists.", + "rspamd_global_filters_regex": "De velden kunnen uitsluitend regular expressions bevatten met het formaat \"/pattern/options\", bijvoorbeeld /.+@domain\\.tld/i.
    Ondanks dat alle invoer wordt gecontroleerd op fouten, is het toch mogelijk dat Rspamd onbruikbaar wordt als deze de invoer niet kan lezen.
    Als je problemen ervaart, herstart Rspamd dan om de filters opnieuw te laten lezen.
    Elementen op de blacklist zijn uitgesloten van de quarantaine.", + "rspamd_settings_map": "Rspamd", + "sal_level": "Moo-level", +@@ -337,7 +342,71 @@ + "admins_ldap": "LDAP administrators", + "api_read_only": "Alleen-lezen toegang", + "api_read_write": "Lees en schrijf toegang", +- "login_time": "Login tijd" ++ "login_time": "Login tijd", ++ "admin_quicklink": "Snelle link naar de admin-loginpagina verbergen", ++ "allowed_methods": "Toegestane toegangsmethoden", ++ "app_hide": "Verberg voor login", ++ "copy_to_clipboard": "Tekst gekopieerd naar het klembord!", ++ "login_page": "Loginpagina", ++ "domainadmin_quicklink": "Snelle link naar de domeinbeheerder-loginpagina verbergen", ++ "f2b_manage_external": "Fail2Ban extern beheren", ++ "f2b_manage_external_info": "Fail2Ban zal nog steeds de banlijst bijhouden, maar zal niet actief regels instellen om verkeer te blokkeren. Gebruik de onderstaande gegenereerde banlijst om het verkeer extern te blokkeren.", ++ "filter": "Filter", ++ "force_sso_text": "Als een externe OIDC-provider is geconfigureerd, verbergt deze optie de standaard Mailcow-loginformulieren en wordt alleen de Single SignOn-knop weergegeven.", ++ "force_sso": "Mailcow-login uitschakelen en alleen Single SignOn tonen", ++ "iam": "Identiteitsprovider", ++ "iam_attribute_field": "Attribuutveld", ++ "iam_authorize_url": "Autorisatie endpoint", ++ "iam_auth_flow": "Autorisatie flow", ++ "iam_auth_flow_info": "Naast de Authorization Code Flow (Standard Flow in Keycloak), die wordt gebruikt voor Single SignOn-login, ondersteunt Mailcow ook een authenticatiestroom met directe inloggegevens. De Mailpassword Flow probeert de gebruikersgegevens te valideren door gebruik te maken van de Keycloak Admin REST API. Mailcow haalt het gehashte wachtwoord op uit het attribuut mailcow_password, dat in Keycloak is gekoppeld.", ++ "iam_client_id": "Client ID", ++ "iam_client_secret": "Client Secret", ++ "iam_client_scopes": "Clientscopes", ++ "iam_default_template": "Standaardsjabloon", ++ "iam_default_template_description": "Als er geen sjabloon aan een gebruiker is toegewezen, wordt het standaardsjabloon gebruikt voor het aanmaken van de mailbox, maar niet voor het bijwerken van de mailbox.", ++ "iam_description": "Configureer een externe provider voor authenticatie. De mailboxen van gebruikers worden automatisch aangemaakt bij hun eerste login, mits er een attribuutkoppeling is ingesteld.", ++ "iam_extra_permission": "Om de volgende instellingen te laten werken, heeft de mailcow-client in Keycloak een service account nodig en de toestemming view-users.", ++ "iam_host": "Hostname", ++ "iam_host_info": "Voer één of meerdere LDAP-hosts in, gescheiden door komma’s.", ++ "iam_import_users": "Importeer gebruikers", ++ "iam_login_provisioning": "Gebruikers automatisch aanmaken bij het inloggen", ++ "iam_mapping": "Attribuutkoppeling", ++ "iam_bindpass": "Bind-wachtwoord", ++ "iam_periodic_full_sync": "Periodieke volledige synchronisatie", ++ "iam_port": "Poort", ++ "iam_realm": "Realm", ++ "iam_redirect_url": "Redirect-URL", ++ "iam_rest_flow": "Mailwachtwoord-flow", ++ "iam_server_url": "Server Url", ++ "iam_sso": "Single SignOn", ++ "iam_sync_interval": "Synchronisatie-/importinterval (min)", ++ "iam_test_connection": "Verbinding testen", ++ "iam_token_url": "Token endpoint", ++ "iam_userinfo_url": "Gebruikersinfo endpoint", ++ "iam_username_field": "Gebruikersnaam veld", ++ "iam_use_ssl": "Gebruik SSL", ++ "iam_use_ssl_info": "Als SSL wordt ingeschakeld en de poort is ingesteld op 389, wordt deze automatisch aangepast naar 636.", ++ "iam_use_tls": "Gebruik StartTLS", ++ "iam_use_tls_info": "Als TLS wordt ingeschakeld, moet je de standaardpoort voor je LDAP-server (389) gebruiken. SSL-poorten kunnen niet worden gebruikt.", ++ "iam_version": "Versie", ++ "ignore_ssl_error": "Negeer SSL foutmeldingen", ++ "ip_check_opt_in": "Kies ervoor om de externe diensten ipv4.mailcow.email en ipv6.mailcow.email te gebruiken om externe IP-adressen te bepalen.", ++ "needs_restart": "vereist een herstart", ++ "no": "✕", ++ "password_reset_info": "Als er geen herstel-e-mailadres is opgegeven, kan deze functie niet worden gebruikt.", ++ "password_reset_settings": "Instellingen voor wachtwoordherstel", ++ "password_reset_tmpl_html": "HTML sjabloon", ++ "password_reset_tmpl_text": "Tekst sjabloon", ++ "password_settings": "Wachtwoordinstellingen", ++ "quicklink_text": "Toon of verberg snelle links naar andere inlogpagina’s onder het inlogformulier", ++ "queue_unban": "deblokkeren", ++ "reset_password_vars": "{{link}} De gegenereerde link om het wachtwoord te resetten
    {{username}} De mailboxnaam van de gebruiker die het wachtwoordherstel heeft aangevraagd
    {{username2}} De naam van de herstelmailbox
    {{date}} De datum waarop het verzoek tot wachtwoordherstel is gedaan
    {{token_lifetime}} De geldigheidsduur van de token in minuten
    {{hostname}} De mailcow-hostnaam", ++ "restore_template": "Leeg laten om het standaardsjabloon te herstellen.", ++ "task": "Taak", ++ "transport_test_rcpt_info": "• Gebruik null@hosted.mailcow.de om relaying naar een externe bestemming te testen.", ++ "user_link": "Gebruikerslink", ++ "user_quicklink": "Snelle link naar de gebruikers-loginpagina verbergen", ++ "yes": "✓" + }, + "danger": { + "access_denied": "Toegang geweigerd of ongeldige gegevens", +@@ -463,7 +532,27 @@ + "demo_mode_enabled": "Demo modus is ingeschakeld", + "template_exists": "Sjabloon %s bestaat al", + "template_id_invalid": "Sjabloon ID %s ongeldig", +- "template_name_invalid": "Sjabloon naam ongeldig" ++ "template_name_invalid": "Sjabloon naam ongeldig", ++ "tfa_removal_blocked": "Twee-factor-authenticatie kan niet worden verwijderd omdat dit vereist is voor uw account.", ++ "authsource_in_use": "De identiteitsprovider kan niet worden gewijzigd of verwijderd omdat deze momenteel door één of meerdere gebruikers wordt gebruikt.", ++ "cors_invalid_origin": "Ongeldige Allow-Origin opgegeven", ++ "extended_sender_acl_denied": "Ontbrekende ACL om externe afzenderadressen in te stellen", ++ "generic_server_error": "Er is een onverwachte serverfout opgetreden. Neem contact op met uw beheerder.", ++ "iam_test_connection": "Verbinding mislukt", ++ "img_dimensions_exceeded": "De afbeelding overschrijdt de maximale afbeeldingsgrootte", ++ "img_size_exceeded": "De afbeelding overschrijdt de maximale afbeeldingsgrootte", ++ "invalid_reset_token": "Ongeldige reset-token", ++ "max_age_invalid": "Maximale leeftijd %s is ongeldig", ++ "mode_invalid": "Mode %s is ongeldig", ++ "mx_invalid": "MX-record %s is ongeldig", ++ "password_reset_invalid_user": "Mailbox niet gevonden of er is geen herstel-e-mailadres ingesteld", ++ "password_reset_na": "Wachtwoordherstel is momenteel niet beschikbaar. Neem contact op met uw beheerder.", ++ "recovery_email_failed": "Kon geen herstel-e-mail verzenden. Neem contact op met uw beheerder.", ++ "required_data_missing": "Vereiste gegevens %s ontbreken", ++ "reset_token_limit_exceeded": "De limiet voor reset-tokens is overschreden. Probeer het later opnieuw.", ++ "to_invalid": "Ontvanger mag niet leeg zijn", ++ "webauthn_username_failed": "De geselecteerde authenticator behoort tot een ander account", ++ "version_invalid": "Versie %s is ongeldig" + }, + "debug": { + "chart_this_server": "Grafiek (deze server)", +@@ -520,7 +609,7 @@ + "alias": "Wijzig alias", + "allow_from_smtp": "Sta enkel de volgende IP-adressen toe voor SMTP", + "allow_from_smtp_info": "Laat leeg om alle afzenders toe te staan.
    IPv4/IPv6-adressen en netwerken.", +- "allowed_protocols": "Toegestane protocollen", ++ "allowed_protocols": "Toegestane protocollen voor directe gebruikerstoegang (heeft geen invloed op protocollen voor app-wachtwoorden).", + "app_name": "Naam van app", + "app_passwd": "Appwachtwoord", + "automap": "Probeer mappen automatisch te koppelen (\"Verzonden items\", \"Verzonden\" => \"Verzonden\" etc.)", +@@ -605,7 +694,7 @@ + "sogo_visible_info": "Wanneer verborgen zal een alias niet worden weergegeven als een selecteerbaar verzendadres. Deze optie beïnvloedt uitsluitend objecten die kunnen worden weergegeven in SOGo (gedeelde of niet-gedeelde aliasadressen die naar minstens één mailbox verwijzen).", + "spam_alias": "Maak een nieuw tijdelijk alias aan, of pas deze aan", + "spam_filter": "Spamfilter", +- "spam_policy": "Voeg items toe of verwijder items van de white- of blacklist", ++ "spam_policy": "Voeg items toe of verwijder items van de deny- en allowlists", + "spam_score": "Stel een aangepaste spamscore in", + "subfolder2": "Synchroniseer in submap op bestemming
    (leeg = gebruik geen submappen)", + "syncjob": "Wijzig sync job", +@@ -624,7 +713,47 @@ + "acl": "ACL (Toestemming)", + "domain_footer": "Domeinbreede footer", + "domain_footer_html": "HTML footer", +- "mailbox_relayhost_info": "Wordt alleen toegepast op de mailbox en directe aliassen, maar heft een domein relayhost op." ++ "mailbox_relayhost_info": "Wordt alleen toegepast op de mailbox en directe aliassen, maar heft een domein relayhost op.", ++ "custom_attributes": "Aangepaste attributen", ++ "domain_footer_info_vars": { ++ "auth_user": "{= auth_user =} - Geauthenticeerde gebruikersnaam opgegeven door een MTA", ++ "from_user": "{= from_user =} - Afzendergedeelte van het e-mailadres, bijvoorbeeld bij \"moo@mailcow.tld\" wordt \"moo\" teruggegeven", ++ "from_name": "{= from_name =} - Naam van de afzender, bijvoorbeeld bij \"Mailcow \" wordt \"Mailcow\" teruggegeven", ++ "from_addr": "{= from_addr =} - Adres van de afzender", ++ "from_domain": "{= from_domain =} - Domein van de afzender", ++ "custom": "{= foo =} - Als de mailbox het aangepaste attribuut \"foo\" met de waarde \"bar\" heeft, wordt \"bar\" teruggegeven." ++ }, ++ "domain_footer_plain": "PLAIN-voettekst", ++ "domain_footer_skip_replies": "Voettekst negeren bij antwoord-e-mails", ++ "footer_exclude": "Uitsluiten van voettekst", ++ "internal": "Intern", ++ "internal_info": "Interne aliassen zijn alleen toegankelijk vanuit het eigen (alias)domein.", ++ "sender_allowed": "Toestaan om als deze alias te verzenden", ++ "sender_allowed_info": "Als dit is uitgeschakeld, kan deze alias alleen e-mail ontvangen. Gebruik de afzender-ACL om dit te overschrijven en specifieke mailboxen toestemming te geven om te verzenden.", ++ "lookup_mx": "Bestemming is een reguliere expressie die wordt gematcht met de MX-naam (.*.google.com om alle e-mail die gericht is aan een MX die eindigt op google.com via deze hop te routeren)", ++ "mailbox_rename": "Hernoem mailbox", ++ "mailbox_rename_agree": "Ik heb een backup gemaakt.", ++ "mailbox_rename_warning": "BELANGRIJK! Maak een back-up voordat u de mailbox hernoemt.", ++ "mailbox_rename_alias": "Alias automatisch aanmaken.", ++ "mailbox_rename_title": "Nieuwe naam van de lokale mailbox", ++ "mta_sts": "MTA-STS", ++ "mta_sts_info": "MTA-STS is een standaard die afdwingt dat e-mailbezorging tussen mailservers TLS met geldige certificaten gebruikt.
    \nDeze wordt gebruikt wanneer DANE niet mogelijk is vanwege ontbrekende of niet-ondersteunde DNSSEC.
    \nOpmerking: Als het ontvangende domein DANE met DNSSEC ondersteunt, heeft DANE altijd de voorkeur – MTA-STS fungeert alleen als een fallback.", ++ "mta_sts_version": "Versie", ++ "mta_sts_version_info": "Definieert de versie van de MTA-STS-standaard – momenteel is alleen STSv1 geldig.", ++ "mta_sts_mode": "Modus", ++ "mta_sts_mode_info": "Er zijn drie modus om uit te kiezen:
    • testing – het beleid wordt alleen gemonitord, overtredingen hebben geen impact.
    • enforce – het beleid wordt strikt afgedwongen, verbindingen zonder geldige TLS worden geweigerd.
    • none – het beleid wordt gepubliceerd maar niet toegepast.
    ", ++ "mta_sts_max_age": "Maximale leeftijd", ++ "mta_sts_max_age_info": "Tijd in seconden dat ontvangende mailservers dit beleid mogen cachen voordat het opnieuw wordt opgehaald.", ++ "mta_sts_mx": "MX server", ++ "mta_sts_mx_info": "Staat verzending alleen toe naar expliciet vermelde mailserver-hostnamen; de verzendende MTA controleert of de DNS MX-hostnaam overeenkomt met de beleidslijst en staat levering alleen toe met een geldig TLS-certificaat (beschermt tegen MITM).", ++ "mta_sts_mx_notice": "Meerdere MX-servers kunnen worden opgegeven (gescheiden door komma’s).", ++ "none_inherit": "Geen / Erven", ++ "password_recovery_email": "E-mail voor wachtwoordherstel", ++ "pushover": "Pushover", ++ "quota_warning_bcc": "Quotum waarschuwing BCC", ++ "quota_warning_bcc_info": "Waarschuwingen zullen in afzonderlijke exemplaren naar de volgende ontvangers worden gestuurd. Het onderwerp zal worden gevolgd door de bijbehorende gebruikersnaam tussen haakjes, bijvoorbeeld: Contingentwaarschuwing (user@example.com).", ++ "sogo_access": "Verleen directe logintoegang tot SOGo", ++ "sogo_access_info": "Na het inloggen wordt de gebruiker automatisch doorgestuurd naar SOGo" + }, + "footer": { + "cancel": "Annuleren", +@@ -637,18 +766,21 @@ + "restart_container": "Herstart container", + "restart_container_info": "Belangrijk: Een herstart kan enige tijd in beslag nemen, wacht aub totdat dit proces voltooid is.
    Deze pagina zal zichzelf verversen zodra het proces voltooid is.", + "restart_now": "Nu herstarten", +- "restarting_container": "Container wordt herstart, even geduld aub..." ++ "restarting_container": "Container wordt herstart, even geduld aub...", ++ "hibp_check": "Controleer tegen haveibeenpwned.com", ++ "nothing_selected": "Niets geselecteerd" + }, + "header": { + "administration": "Configuratie & details", + "apps": "Apps", +- "debug": "Systeeminformatie", ++ "debug": "Informatie", + "email": "E-Mail", + "mailcow_config": "Beheer", + "quarantine": "Quarantaine", + "restart_netfilter": "Herstart netfilter", + "restart_sogo": "Herstart SOGo", +- "user_settings": "Gebruikersinstellingen" ++ "user_settings": "Gebruikersinstellingen", ++ "mailcow_system": "Systeem" + }, + "info": { + "awaiting_tfa_confirmation": "In afwachting van tweefactorauthenticatie...", +@@ -662,7 +794,22 @@ + "mobileconfig_info": "Log in als mailboxgebruiker om het Apple-verbindingsprofiel te downloaden.", + "other_logins": "of aanmelden met", + "password": "Wachtwoord", +- "username": "Gebruikersnaam" ++ "username": "Gebruikersnaam", ++ "back_to_mailcow": "Terug naar mailcow", ++ "forgot_password": "> Wachtwoord vergeten?", ++ "invalid_pass_reset_token": "De reset-wachtwoordtoken is ongeldig of verlopen.
    Vraag een nieuwe link voor het resetten van het wachtwoord aan.", ++ "login_linkstext": "Niet de juiste login?", ++ "login_usertext": "Log in als gebruiker", ++ "login_domainadmintext": "Login in als domeinbeheerder", ++ "login_admintext": "Log in als administrator", ++ "login_user": "Gebruikerslogin", ++ "login_dadmin": "Domeinbeheerder login", ++ "login_admin": "Administrator login", ++ "new_password": "Nieuw wachtwoord", ++ "new_password_confirm": "Bevestig nieuw wachtwoord", ++ "reset_password": "Herstel wachtwoord", ++ "request_reset_password": "Verzoek wachtwoord wijziging", ++ "email": "E-mailadres" + }, + "mailbox": { + "action": "Handeling", +@@ -782,7 +929,7 @@ + "sieve_preset_5": "Autoreply (vakantie)", + "sieve_preset_6": "Weiger mail met antwoord", + "sieve_preset_7": "Forward en behoud/verwijder", +- "sieve_preset_8": "Verwijder mail verstuurd naar een aliasadres van de afzender", ++ "sieve_preset_8": "E-mail van een specifieke afzender doorsturen, als gelezen markeren en in een submap plaatsen", + "sieve_preset_header": "Zie de onderstaande voorbeelden. Raadpleeg Wikipedia voor meer informatie.", + "sogo_visible": "Alias tonen in SOGo", + "sogo_visible_n": "Verberg alias in SOGo", +@@ -809,7 +956,37 @@ + "toggle_all": "Selecteer alles", + "username": "Gebruikersnaam", + "waiting": "Wachten", +- "weekly": "Wekelijks" ++ "weekly": "Wekelijks", ++ "add_alias_expand": "Alias uitbreiden over alias-domeinen", ++ "add_template": "Sjabloon toevoegen", ++ "all_domains": "Alle domeinen", ++ "catch_all": "Catch-All", ++ "created_on": "Aangemaakt op", ++ "domain_templates": "Domein sjablonen", ++ "domain_quota_total": "Totale domein-opslagruimte", ++ "goto_ham": "Leren als Ham", ++ "goto_spam": "Leren als spam", ++ "iam": "Identiteitsprovider", ++ "internal": "Intern", ++ "last_pw_change": "Laatste wachtwoordwijziging", ++ "mailbox_templates": "Mailbox sjablonen", ++ "no": "✕", ++ "open_logs": "Open logs", ++ "recipient": "Ontvanger", ++ "relay_unknown": "Onbekende mailboxen relayen", ++ "sender": "Afzender", ++ "syncjob_check_log": "Controleer log", ++ "syncjob_last_run_result": "Laatste uitvoeringsresultaat", ++ "syncjob_EX_OK": "Succes", ++ "syncjob_EXIT_CONNECTION_FAILURE": "Verbindingsprobleem", ++ "syncjob_EXIT_TLS_FAILURE": "Probleem met versleutelde verbinding", ++ "syncjob_EXIT_AUTHENTICATION_FAILURE": "Authenticatieprobleem", ++ "syncjob_EXIT_OVERQUOTA": "Doel mailbox is over quota", ++ "syncjob_EXIT_CONNECTION_FAILURE_HOST1": "Kan geen verbinding maken met de externe server", ++ "syncjob_EXIT_AUTHENTICATION_FAILURE_USER1": "Verkeerde gebruikersnaam of wachtwoord", ++ "templates": "Sjablonen", ++ "template": "Sjabloon", ++ "yes": "✓" + }, + "oauth2": { + "access_denied": "Log in als een mailboxgebruiker om toegang via OAuth te verlenen", +@@ -842,7 +1019,7 @@ + "notified": "Verwittigd", + "qhandler_success": "Aanvraag succesvol verzonden naar het systeem. Je kunt nu het venster sluiten.", + "qid": "Rspamd QID", +- "qinfo": "Het quarantainesysteem slaat een kopie van zowel geweigerde mail (voor de afzender zal het lijken alsof de mail niet afgeleverd is), als mail die afgeleverd is de spamfolder, op in de database.\r\n
    \"Markeer als spam en verwijder\" traint het systeem om soortgelijke mails in de toekomst opnieuw als spam te markeren.\r\n
    Wanneer er meerdere berichten tegelijkertijd worden behandeld kan het mogelijk enige tijd duren.
    Elementen op de blacklist zijn uitgesloten van de quarantaine.", ++ "qinfo": "Het quarantainesysteem slaat een kopie van zowel geweigerde mail (voor de afzender zal het lijken alsof de mail niet afgeleverd is), als mail die afgeleverd is de spamfolder, op in de database.\n
    \"Markeer als spam en verwijder\" traint het systeem om soortgelijke mails in de toekomst opnieuw als spam te markeren.\n
    Wanneer er meerdere berichten tegelijkertijd worden behandeld kan het mogelijk enige tijd duren.
    Elementen op de denylist zijn uitgesloten van de quarantaine.", + "qitem": "Quarantaine-item", + "quarantine": "Quarantaine", + "quick_actions": "Handelingen", +@@ -874,7 +1051,19 @@ + "toggle_all": "Selecteer alles" + }, + "queue": { +- "queue_manager": "Queue manager" ++ "queue_manager": "Queue manager", ++ "delete": "Verwijder alles", ++ "flush": "Wachtrij leegmaken", ++ "info": "De mailwachtrij bevat alle e-mails die wachten op aflevering. Als een e-mail lange tijd in de mailwachtrij blijft staan, wordt deze automatisch door het systeem verwijderd.
    De foutmelding van de betreffende e-mail geeft informatie over waarom de e-mail niet kon worden afgeleverd.", ++ "legend": "Functies voor acties in de mailwachtrij:", ++ "ays": "Bevestig dat u alle items uit de huidige wachtrij wilt verwijderen.", ++ "deliver_mail": "Afleveren", ++ "deliver_mail_legend": "Probeert de geselecteerde e-mails opnieuw te bezorgen.", ++ "hold_mail": "Vasthouden", ++ "hold_mail_legend": "Houdt de geselecteerde e-mails vast. (Voorkomt verdere afleverpogingen)", ++ "show_message": "Bericht weergeven", ++ "unban": "Wachtrij deblokkeren", ++ "unhold_mail": "Vrijgeven" + }, + "start": { + "help": "Toon/verberg hulppaneel", +@@ -994,7 +1183,8 @@ + "start_fido2_validation": "Start FIDO2-validatie", + "fido2_auth": "Aanmelden met FIDO2", + "fido2_success": "Apparaat succesvol geregistreerd", +- "fido2_validation_failed": "Validatie mislukt" ++ "fido2_validation_failed": "Validatie mislukt", ++ "set_fido2_touchid": "Registreer Touch ID op Apple M1" + }, + "user": { + "action": "Handeling", +@@ -1161,6 +1351,7 @@ + "loadingRecords": "Laden...", + "processing": "Wachten alstublieft..", + "search": "Zoeken:", +- "zeroRecords": "Geen overeenkomsten gevonden" ++ "zeroRecords": "Geen overeenkomsten gevonden", ++ "infoFiltered": "(gefilterd uit _MAX_ totale vermeldingen)" + } + } diff --git a/tasks/mailcow__mailcow-dockerized-7095/tests/test.sh b/tasks/mailcow__mailcow-dockerized-7095/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..1319bc42f02f7f8efea488678e95850a632c3851 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7095/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace fe71f84c822c69104c61ac8f6bc9c6f299366d76 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/mailcow__mailcow-dockerized-7095/tests/verifier.py b/tasks/mailcow__mailcow-dockerized-7095/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7095/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/mailcow__mailcow-dockerized-7098/environment/Dockerfile b/tasks/mailcow__mailcow-dockerized-7098/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6788ab79871813ed4fcaff65a77f876c160b9bf9 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7098/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/mailcow/mailcow-dockerized.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/mailcow/mailcow-dockerized.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/mailcow/mailcow-dockerized.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 905e93627c7d8ce884732661c90dd4bd8596d7d4 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 905e93627c7d8ce884732661c90dd4bd8596d7d4 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 905e93627c7d8ce884732661c90dd4bd8596d7d4 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/mailcow__mailcow-dockerized-7098/instruction.md b/tasks/mailcow__mailcow-dockerized-7098/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..bee3cd16cc1b3839fbeb7fd5061b70963a4efb05 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7098/instruction.md @@ -0,0 +1,40 @@ +# Issue + +**Title:** [SOGo] Update to 5.12.5 + +## Description + + + +## Contribution Guidelines + +* [x] I've read the [contribution guidelines](https://github.com/mailcow/mailcow-dockerized/blob/master/CONTRIBUTING.md) and wholeheartedly agree them + + + +## What does this PR include? + +### Short Description + +This PR Updates SOGo to 5.12.5 + +### Affected Containers + + + + + +- sogo-mailcow + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `905e93627c7d`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/mailcow__mailcow-dockerized-7098/solution/patch.diff b/tasks/mailcow__mailcow-dockerized-7098/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..88cdc08cc4f4597510604ece394ed345a60c683c --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7098/solution/patch.diff @@ -0,0 +1,40 @@ +diff --git a/data/Dockerfiles/sogo/Dockerfile b/data/Dockerfiles/sogo/Dockerfile +index 8ec90ae3..d118b649 100644 +--- a/data/Dockerfiles/sogo/Dockerfile ++++ b/data/Dockerfiles/sogo/Dockerfile +@@ -3,7 +3,7 @@ + # Version: SOGo-5.12.4 + # + # Applied security patches: +-# - 16ab99e7cf8db2c30b211f0d5e338d7f9e3a9efb: XSS vulnerability in theme parameter ++# - + # + # To add new patches, modify SOGO_SECURITY_PATCHES ARG below with space-separated commit hashes + +@@ -12,10 +12,10 @@ FROM debian:bookworm + LABEL maintainer="The Infrastructure Company GmbH " + + ARG DEBIAN_FRONTEND=noninteractive +-ARG SOGO_VERSION=SOGo-5.12.4 +-ARG SOPE_VERSION=SOPE-5.12.4 ++ARG SOGO_VERSION=SOGo-5.12.5 ++ARG SOPE_VERSION=SOPE-5.12.5 + # Security patches to apply (space-separated commit hashes) +-ARG SOGO_SECURITY_PATCHES="16ab99e7cf8db2c30b211f0d5e338d7f9e3a9efb" ++ARG SOGO_SECURITY_PATCHES="" + # renovate: datasource=github-releases depName=tianon/gosu versioning=semver-coerced extractVersion=^(?.*)$ + ARG GOSU_VERSION=1.19 + ENV LC_ALL=C +diff --git a/docker-compose.yml b/docker-compose.yml +index 7d994e94..a271118a 100644 +--- a/docker-compose.yml ++++ b/docker-compose.yml +@@ -200,7 +200,7 @@ services: + - phpfpm + + sogo-mailcow: +- image: ghcr.io/mailcow/sogo:5.12.4-2 ++ image: ghcr.io/mailcow/sogo:5.12.5-1 + environment: + - DBNAME=${DBNAME} + - DBUSER=${DBUSER} diff --git a/tasks/mailcow__mailcow-dockerized-7098/solution/solve.sh b/tasks/mailcow__mailcow-dockerized-7098/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7098/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/mailcow__mailcow-dockerized-7098/task.toml b/tasks/mailcow__mailcow-dockerized-7098/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..083171525148756e4d2fc01f14df986d60a8f471 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7098/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/mailcow__mailcow-dockerized-7098" +description = "[SOGo] Update to 5.12.5" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "mailcow-dockerized", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "mailcow/mailcow-dockerized" +ref = "905e93627c7d8ce884732661c90dd4bd8596d7d4" +reference = "https://github.com/mailcow/mailcow-dockerized/pull/7098" +source_access = "auto" +built_at = "2026-11-16T16:09:53.219938+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:9097e438e4e6293e97e836efa0f18f4a5ce8b12b3399eeafed91ce982c3efc16" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-03-06T08:21:09Z" +diff_format = "unified" +context_files = [ + "data/Dockerfiles/sogo/Dockerfile", + "docker-compose.yml", +] +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.442087+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:18d9442bb55d5869f86654b6681c39e584e3862d0f145906be30da56fbf939cc" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/mailcow__mailcow-dockerized-7098/tests/capture.py b/tasks/mailcow__mailcow-dockerized-7098/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7098/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/mailcow__mailcow-dockerized-7098/tests/instruction.md b/tasks/mailcow__mailcow-dockerized-7098/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..bee3cd16cc1b3839fbeb7fd5061b70963a4efb05 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7098/tests/instruction.md @@ -0,0 +1,40 @@ +# Issue + +**Title:** [SOGo] Update to 5.12.5 + +## Description + + + +## Contribution Guidelines + +* [x] I've read the [contribution guidelines](https://github.com/mailcow/mailcow-dockerized/blob/master/CONTRIBUTING.md) and wholeheartedly agree them + + + +## What does this PR include? + +### Short Description + +This PR Updates SOGo to 5.12.5 + +### Affected Containers + + + + + +- sogo-mailcow + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `905e93627c7d`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/mailcow__mailcow-dockerized-7098/tests/oracle.patch b/tasks/mailcow__mailcow-dockerized-7098/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..88cdc08cc4f4597510604ece394ed345a60c683c --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7098/tests/oracle.patch @@ -0,0 +1,40 @@ +diff --git a/data/Dockerfiles/sogo/Dockerfile b/data/Dockerfiles/sogo/Dockerfile +index 8ec90ae3..d118b649 100644 +--- a/data/Dockerfiles/sogo/Dockerfile ++++ b/data/Dockerfiles/sogo/Dockerfile +@@ -3,7 +3,7 @@ + # Version: SOGo-5.12.4 + # + # Applied security patches: +-# - 16ab99e7cf8db2c30b211f0d5e338d7f9e3a9efb: XSS vulnerability in theme parameter ++# - + # + # To add new patches, modify SOGO_SECURITY_PATCHES ARG below with space-separated commit hashes + +@@ -12,10 +12,10 @@ FROM debian:bookworm + LABEL maintainer="The Infrastructure Company GmbH " + + ARG DEBIAN_FRONTEND=noninteractive +-ARG SOGO_VERSION=SOGo-5.12.4 +-ARG SOPE_VERSION=SOPE-5.12.4 ++ARG SOGO_VERSION=SOGo-5.12.5 ++ARG SOPE_VERSION=SOPE-5.12.5 + # Security patches to apply (space-separated commit hashes) +-ARG SOGO_SECURITY_PATCHES="16ab99e7cf8db2c30b211f0d5e338d7f9e3a9efb" ++ARG SOGO_SECURITY_PATCHES="" + # renovate: datasource=github-releases depName=tianon/gosu versioning=semver-coerced extractVersion=^(?.*)$ + ARG GOSU_VERSION=1.19 + ENV LC_ALL=C +diff --git a/docker-compose.yml b/docker-compose.yml +index 7d994e94..a271118a 100644 +--- a/docker-compose.yml ++++ b/docker-compose.yml +@@ -200,7 +200,7 @@ services: + - phpfpm + + sogo-mailcow: +- image: ghcr.io/mailcow/sogo:5.12.4-2 ++ image: ghcr.io/mailcow/sogo:5.12.5-1 + environment: + - DBNAME=${DBNAME} + - DBUSER=${DBUSER} diff --git a/tasks/mailcow__mailcow-dockerized-7098/tests/test.sh b/tasks/mailcow__mailcow-dockerized-7098/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b129ba1725408073bd767612a4f88ada7d1f40f4 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7098/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 905e93627c7d8ce884732661c90dd4bd8596d7d4 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/mailcow__mailcow-dockerized-7098/tests/verifier.py b/tasks/mailcow__mailcow-dockerized-7098/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7098/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/mailcow__mailcow-dockerized-7100/environment/Dockerfile b/tasks/mailcow__mailcow-dockerized-7100/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6d254a9553877f987dd90a34a495436fdc66fc5d --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7100/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/mailcow/mailcow-dockerized.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/mailcow/mailcow-dockerized.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/mailcow/mailcow-dockerized.git +WORKDIR /workspace +RUN git fetch --depth 1 origin e84822606253172641d5e4a7fe99b8326b4dc0e3 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard e84822606253172641d5e4a7fe99b8326b4dc0e3 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base e84822606253172641d5e4a7fe99b8326b4dc0e3 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/mailcow__mailcow-dockerized-7100/instruction.md b/tasks/mailcow__mailcow-dockerized-7100/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c29e9e13b9944332dfdf17f80d07cebbfe5ee3a1 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7100/instruction.md @@ -0,0 +1,39 @@ +# Issue + +**Title:** [Rspamd] Update to 3.14.3-1 + +## Description + + + +## Contribution Guidelines + +* [x] I've read the [contribution guidelines](https://github.com/mailcow/mailcow-dockerized/blob/master/CONTRIBUTING.md) and wholeheartedly agree them + + + +## What does this PR include? + +### Short Description + +Update Rspamd to version 3.14.3-1 + +### Affected Containers + + + + +- rspamd-mailcow + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `e84822606253`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/mailcow__mailcow-dockerized-7100/solution/patch.diff b/tasks/mailcow__mailcow-dockerized-7100/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..cb8a9f9b45cd4da86dfcb351c5703e29b03417cc --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7100/solution/patch.diff @@ -0,0 +1,26 @@ +diff --git a/data/Dockerfiles/rspamd/Dockerfile b/data/Dockerfiles/rspamd/Dockerfile +index 55bcc957..d0c71042 100644 +--- a/data/Dockerfiles/rspamd/Dockerfile ++++ b/data/Dockerfiles/rspamd/Dockerfile +@@ -2,7 +2,7 @@ FROM debian:trixie-slim + LABEL maintainer="The Infrastructure Company GmbH " + + ARG DEBIAN_FRONTEND=noninteractive +-ARG RSPAMD_VER=rspamd_3.14.2-82~90302bc ++ARG RSPAMD_VER=rspamd_3.14.3-1~236eb65 + ARG CODENAME=trixie + ENV LC_ALL=C + +diff --git a/docker-compose.yml b/docker-compose.yml +index 7d62c082..fbf1125f 100644 +--- a/docker-compose.yml ++++ b/docker-compose.yml +@@ -84,7 +84,7 @@ services: + - clamd + + rspamd-mailcow: +- image: ghcr.io/mailcow/rspamd:3.14.2 ++ image: ghcr.io/mailcow/rspamd:3.14.3-1 + stop_grace_period: 30s + depends_on: + - dovecot-mailcow diff --git a/tasks/mailcow__mailcow-dockerized-7100/solution/solve.sh b/tasks/mailcow__mailcow-dockerized-7100/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7100/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/mailcow__mailcow-dockerized-7100/task.toml b/tasks/mailcow__mailcow-dockerized-7100/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..3dbbe919ebd5f0c27ccf36eb49bc771fa2fde6c1 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7100/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/mailcow__mailcow-dockerized-7100" +description = "[Rspamd] Update to 3.14.3-1" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "mailcow-dockerized", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "mailcow/mailcow-dockerized" +ref = "e84822606253172641d5e4a7fe99b8326b4dc0e3" +reference = "https://github.com/mailcow/mailcow-dockerized/pull/7100" +source_access = "auto" +built_at = "2026-11-16T16:09:53.221366+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:93e2aea8f7a97b89b4b574b7a374e57e3f7b04981a59685ba1c4adb51e51b86b" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-03-09T07:15:11Z" +diff_format = "unified" +context_files = [ + "data/Dockerfiles/rspamd/Dockerfile", + "docker-compose.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.442563+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:3448757f288fbd218c77136b70ec30ab6221d2d152279a376184de5681e91fe9" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/mailcow__mailcow-dockerized-7100/tests/capture.py b/tasks/mailcow__mailcow-dockerized-7100/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7100/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/mailcow__mailcow-dockerized-7100/tests/instruction.md b/tasks/mailcow__mailcow-dockerized-7100/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c29e9e13b9944332dfdf17f80d07cebbfe5ee3a1 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7100/tests/instruction.md @@ -0,0 +1,39 @@ +# Issue + +**Title:** [Rspamd] Update to 3.14.3-1 + +## Description + + + +## Contribution Guidelines + +* [x] I've read the [contribution guidelines](https://github.com/mailcow/mailcow-dockerized/blob/master/CONTRIBUTING.md) and wholeheartedly agree them + + + +## What does this PR include? + +### Short Description + +Update Rspamd to version 3.14.3-1 + +### Affected Containers + + + + +- rspamd-mailcow + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `e84822606253`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/mailcow__mailcow-dockerized-7100/tests/oracle.patch b/tasks/mailcow__mailcow-dockerized-7100/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..cb8a9f9b45cd4da86dfcb351c5703e29b03417cc --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7100/tests/oracle.patch @@ -0,0 +1,26 @@ +diff --git a/data/Dockerfiles/rspamd/Dockerfile b/data/Dockerfiles/rspamd/Dockerfile +index 55bcc957..d0c71042 100644 +--- a/data/Dockerfiles/rspamd/Dockerfile ++++ b/data/Dockerfiles/rspamd/Dockerfile +@@ -2,7 +2,7 @@ FROM debian:trixie-slim + LABEL maintainer="The Infrastructure Company GmbH " + + ARG DEBIAN_FRONTEND=noninteractive +-ARG RSPAMD_VER=rspamd_3.14.2-82~90302bc ++ARG RSPAMD_VER=rspamd_3.14.3-1~236eb65 + ARG CODENAME=trixie + ENV LC_ALL=C + +diff --git a/docker-compose.yml b/docker-compose.yml +index 7d62c082..fbf1125f 100644 +--- a/docker-compose.yml ++++ b/docker-compose.yml +@@ -84,7 +84,7 @@ services: + - clamd + + rspamd-mailcow: +- image: ghcr.io/mailcow/rspamd:3.14.2 ++ image: ghcr.io/mailcow/rspamd:3.14.3-1 + stop_grace_period: 30s + depends_on: + - dovecot-mailcow diff --git a/tasks/mailcow__mailcow-dockerized-7100/tests/test.sh b/tasks/mailcow__mailcow-dockerized-7100/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..04fa875de43689d8425af8d1b35e1504f0fb6827 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7100/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace e84822606253172641d5e4a7fe99b8326b4dc0e3 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/mailcow__mailcow-dockerized-7100/tests/verifier.py b/tasks/mailcow__mailcow-dockerized-7100/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7100/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/mailcow__mailcow-dockerized-7103/environment/Dockerfile b/tasks/mailcow__mailcow-dockerized-7103/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..911e89ca0f264fa5b5945e8c54c000d130665b28 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7103/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/mailcow/mailcow-dockerized.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/mailcow/mailcow-dockerized.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/mailcow/mailcow-dockerized.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 8f883f3d374b4de9b3ad731d3bef5d667b095ae8 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 8f883f3d374b4de9b3ad731d3bef5d667b095ae8 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 8f883f3d374b4de9b3ad731d3bef5d667b095ae8 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/mailcow__mailcow-dockerized-7103/instruction.md b/tasks/mailcow__mailcow-dockerized-7103/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ef1287e938a1e9ee4e4cf5382a805417c74a4a4a --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7103/instruction.md @@ -0,0 +1,31 @@ +# Issue + +**Title:** [Watchdog] Fix Nagios MariaDB client SSL compatibility with Alpine 3.23 + +## Description + + + +## Contribution Guidelines + +* [x] I've read the [contribution guidelines](https://github.com/mailcow/mailcow-dockerized/blob/master/CONTRIBUTING.md) and wholeheartedly agree them + + + +## What does this PR include? + +### Short Description + +This PR fixes MySQL/MariaDB SSL compatibility issues introduced with Alpine 3.23, which ships MariaDB client 11.4.9. The new client version enforces SSL by default, causing watchdog health checks to fail with "TLS/SSL error: SSL is required, but the server does not support it" even when using Unix socket connections. + +The fix adds a MySQL client configuration file for Nagios Plugins that disables SSL for Unix socket connections and updates all Nagios plugin calls to use this configuration. + +Fixes: +- #7102 +### Affected Containers + +- watchdog-mailcow + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `8f883f3d374b`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/mailcow__mailcow-dockerized-7103/solution/patch.diff b/tasks/mailcow__mailcow-dockerized-7103/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..8ed7ed881d0185647f1b04daf15c44811e904c0b --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7103/solution/patch.diff @@ -0,0 +1,66 @@ +diff --git a/data/Dockerfiles/watchdog/Dockerfile b/data/Dockerfiles/watchdog/Dockerfile +index 83108673..54854ea1 100644 +--- a/data/Dockerfiles/watchdog/Dockerfile ++++ b/data/Dockerfiles/watchdog/Dockerfile +@@ -37,5 +37,6 @@ RUN apk add --update \ + COPY watchdog.sh /watchdog.sh + COPY check_mysql_slavestatus.sh /usr/lib/nagios/plugins/check_mysql_slavestatus.sh + COPY check_dns.sh /usr/lib/mailcow/check_dns.sh ++COPY client.cnf /etc/my.cnf.d/client.cnf + + CMD ["/watchdog.sh"] +diff --git a/data/Dockerfiles/watchdog/client.cnf b/data/Dockerfiles/watchdog/client.cnf +new file mode 100644 +index 00000000..f078f3cb +--- /dev/null ++++ b/data/Dockerfiles/watchdog/client.cnf +@@ -0,0 +1,3 @@ ++[client] ++ssl = false ++ssl-verify-server-cert = false +diff --git a/data/Dockerfiles/watchdog/watchdog.sh b/data/Dockerfiles/watchdog/watchdog.sh +index 558aaa19..020f3f83 100755 +--- a/data/Dockerfiles/watchdog/watchdog.sh ++++ b/data/Dockerfiles/watchdog/watchdog.sh +@@ -38,7 +38,7 @@ if [[ ! -p /tmp/com_pipe ]]; then + fi + + # Wait for containers +-while ! mariadb-admin status --ssl=false --socket=/var/run/mysqld/mysqld.sock -u${DBUSER} -p${DBPASS} --silent; do ++while ! mariadb-admin status --skip-ssl --socket=/var/run/mysqld/mysqld.sock -u${DBUSER} -p${DBPASS} --silent; do + echo "Waiting for SQL..." + sleep 2 + done +@@ -359,8 +359,8 @@ mysql_checks() { + while [ ${err_count} -lt ${THRESHOLD} ]; do + touch /tmp/mysql-mailcow; echo "$(tail -50 /tmp/mysql-mailcow)" > /tmp/mysql-mailcow + err_c_cur=${err_count} +- /usr/lib/nagios/plugins/check_mysql -s /var/run/mysqld/mysqld.sock -u ${DBUSER} -p ${DBPASS} -d ${DBNAME} 2>> /tmp/mysql-mailcow 1>&2; err_count=$(( ${err_count} + $? )) +- /usr/lib/nagios/plugins/check_mysql_query -s /var/run/mysqld/mysqld.sock -u ${DBUSER} -p ${DBPASS} -d ${DBNAME} -q "SELECT COUNT(*) FROM information_schema.tables" 2>> /tmp/mysql-mailcow 1>&2; err_count=$(( ${err_count} + $? )) ++ /usr/lib/nagios/plugins/check_mysql -f /etc/my.cnf.d/client.cnf -s /var/run/mysqld/mysqld.sock -u ${DBUSER} -p ${DBPASS} -d ${DBNAME} 2>> /tmp/mysql-mailcow 1>&2; err_count=$(( ${err_count} + $? )) ++ /usr/lib/nagios/plugins/check_mysql_query -f /etc/my.cnf.d/client.cnf -s /var/run/mysqld/mysqld.sock -u ${DBUSER} -p ${DBPASS} -d ${DBNAME} -q "SELECT COUNT(*) FROM information_schema.tables" 2>> /tmp/mysql-mailcow 1>&2; err_count=$(( ${err_count} + $? )) + [ ${err_c_cur} -eq ${err_count} ] && [ ! $((${err_count} - 1)) -lt 0 ] && err_count=$((${err_count} - 1)) diff_c=1 + [ ${err_c_cur} -ne ${err_count} ] && diff_c=$(( ${err_c_cur} - ${err_count} )) + progress "MySQL/MariaDB" ${THRESHOLD} $(( ${THRESHOLD} - ${err_count} )) ${diff_c} +@@ -384,7 +384,7 @@ mysql_repl_checks() { + while [ ${err_count} -lt ${THRESHOLD} ]; do + touch /tmp/mysql_repl_checks; echo "$(tail -50 /tmp/mysql_repl_checks)" > /tmp/mysql_repl_checks + err_c_cur=${err_count} +- /usr/lib/nagios/plugins/check_mysql_slavestatus.sh -S /var/run/mysqld/mysqld.sock -u root -p ${DBROOT} 2>> /tmp/mysql_repl_checks 1>&2; err_count=$(( ${err_count} + $? )) ++ /usr/lib/nagios/plugins/check_mysql_slavestatus.sh -o /etc/my.cnf.d/client.cnf -S /var/run/mysqld/mysqld.sock -u root -p ${DBROOT} 2>> /tmp/mysql_repl_checks 1>&2; err_count=$(( ${err_count} + $? )) + [ ${err_c_cur} -eq ${err_count} ] && [ ! $((${err_count} - 1)) -lt 0 ] && err_count=$((${err_count} - 1)) diff_c=1 + [ ${err_c_cur} -ne ${err_count} ] && diff_c=$(( ${err_c_cur} - ${err_count} )) + progress "MySQL/MariaDB replication" ${THRESHOLD} $(( ${THRESHOLD} - ${err_count} )) ${diff_c} +diff --git a/docker-compose.yml b/docker-compose.yml +index fbf1125f..1d77b9b8 100644 +--- a/docker-compose.yml ++++ b/docker-compose.yml +@@ -526,7 +526,7 @@ services: + - /lib/modules:/lib/modules:ro + + watchdog-mailcow: +- image: ghcr.io/mailcow/watchdog:2.10 ++ image: ghcr.io/mailcow/watchdog:2.11 + dns: + - ${IPV4_NETWORK:-172.22.1}.254 + tmpfs: diff --git a/tasks/mailcow__mailcow-dockerized-7103/solution/solve.sh b/tasks/mailcow__mailcow-dockerized-7103/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7103/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/mailcow__mailcow-dockerized-7103/task.toml b/tasks/mailcow__mailcow-dockerized-7103/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..83370d88c5ad5989c49ecc2e497ebee2e06c47a9 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7103/task.toml @@ -0,0 +1,71 @@ +version = "1.0" + +[task] +name = "trending/mailcow__mailcow-dockerized-7103" +description = "[Watchdog] Fix Nagios MariaDB client SSL compatibility with Alpine 3.23" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "mailcow-dockerized", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "mailcow/mailcow-dockerized" +ref = "8f883f3d374b4de9b3ad731d3bef5d667b095ae8" +reference = "https://github.com/mailcow/mailcow-dockerized/pull/7103" +source_access = "auto" +built_at = "2026-11-16T16:09:53.215274+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:26e59ad9f739f46c71b4f237625de4bc64925ccf2c41d83f8a9d14fd6c2ffed9" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-03-10T09:04:18Z" +diff_format = "unified" +context_files = [ + "data/Dockerfiles/watchdog/Dockerfile", + "data/Dockerfiles/watchdog/client.cnf", + "data/Dockerfiles/watchdog/watchdog.sh", + "docker-compose.yml", +] +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.443074+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:a60a72d1f42d08b974f0e0b97e7796bdf1a8ca5f3d7d4d1943292db40458dc7a" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/mailcow__mailcow-dockerized-7103/tests/capture.py b/tasks/mailcow__mailcow-dockerized-7103/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7103/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/mailcow__mailcow-dockerized-7103/tests/instruction.md b/tasks/mailcow__mailcow-dockerized-7103/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ef1287e938a1e9ee4e4cf5382a805417c74a4a4a --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7103/tests/instruction.md @@ -0,0 +1,31 @@ +# Issue + +**Title:** [Watchdog] Fix Nagios MariaDB client SSL compatibility with Alpine 3.23 + +## Description + + + +## Contribution Guidelines + +* [x] I've read the [contribution guidelines](https://github.com/mailcow/mailcow-dockerized/blob/master/CONTRIBUTING.md) and wholeheartedly agree them + + + +## What does this PR include? + +### Short Description + +This PR fixes MySQL/MariaDB SSL compatibility issues introduced with Alpine 3.23, which ships MariaDB client 11.4.9. The new client version enforces SSL by default, causing watchdog health checks to fail with "TLS/SSL error: SSL is required, but the server does not support it" even when using Unix socket connections. + +The fix adds a MySQL client configuration file for Nagios Plugins that disables SSL for Unix socket connections and updates all Nagios plugin calls to use this configuration. + +Fixes: +- #7102 +### Affected Containers + +- watchdog-mailcow + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `8f883f3d374b`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/mailcow__mailcow-dockerized-7103/tests/oracle.patch b/tasks/mailcow__mailcow-dockerized-7103/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..8ed7ed881d0185647f1b04daf15c44811e904c0b --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7103/tests/oracle.patch @@ -0,0 +1,66 @@ +diff --git a/data/Dockerfiles/watchdog/Dockerfile b/data/Dockerfiles/watchdog/Dockerfile +index 83108673..54854ea1 100644 +--- a/data/Dockerfiles/watchdog/Dockerfile ++++ b/data/Dockerfiles/watchdog/Dockerfile +@@ -37,5 +37,6 @@ RUN apk add --update \ + COPY watchdog.sh /watchdog.sh + COPY check_mysql_slavestatus.sh /usr/lib/nagios/plugins/check_mysql_slavestatus.sh + COPY check_dns.sh /usr/lib/mailcow/check_dns.sh ++COPY client.cnf /etc/my.cnf.d/client.cnf + + CMD ["/watchdog.sh"] +diff --git a/data/Dockerfiles/watchdog/client.cnf b/data/Dockerfiles/watchdog/client.cnf +new file mode 100644 +index 00000000..f078f3cb +--- /dev/null ++++ b/data/Dockerfiles/watchdog/client.cnf +@@ -0,0 +1,3 @@ ++[client] ++ssl = false ++ssl-verify-server-cert = false +diff --git a/data/Dockerfiles/watchdog/watchdog.sh b/data/Dockerfiles/watchdog/watchdog.sh +index 558aaa19..020f3f83 100755 +--- a/data/Dockerfiles/watchdog/watchdog.sh ++++ b/data/Dockerfiles/watchdog/watchdog.sh +@@ -38,7 +38,7 @@ if [[ ! -p /tmp/com_pipe ]]; then + fi + + # Wait for containers +-while ! mariadb-admin status --ssl=false --socket=/var/run/mysqld/mysqld.sock -u${DBUSER} -p${DBPASS} --silent; do ++while ! mariadb-admin status --skip-ssl --socket=/var/run/mysqld/mysqld.sock -u${DBUSER} -p${DBPASS} --silent; do + echo "Waiting for SQL..." + sleep 2 + done +@@ -359,8 +359,8 @@ mysql_checks() { + while [ ${err_count} -lt ${THRESHOLD} ]; do + touch /tmp/mysql-mailcow; echo "$(tail -50 /tmp/mysql-mailcow)" > /tmp/mysql-mailcow + err_c_cur=${err_count} +- /usr/lib/nagios/plugins/check_mysql -s /var/run/mysqld/mysqld.sock -u ${DBUSER} -p ${DBPASS} -d ${DBNAME} 2>> /tmp/mysql-mailcow 1>&2; err_count=$(( ${err_count} + $? )) +- /usr/lib/nagios/plugins/check_mysql_query -s /var/run/mysqld/mysqld.sock -u ${DBUSER} -p ${DBPASS} -d ${DBNAME} -q "SELECT COUNT(*) FROM information_schema.tables" 2>> /tmp/mysql-mailcow 1>&2; err_count=$(( ${err_count} + $? )) ++ /usr/lib/nagios/plugins/check_mysql -f /etc/my.cnf.d/client.cnf -s /var/run/mysqld/mysqld.sock -u ${DBUSER} -p ${DBPASS} -d ${DBNAME} 2>> /tmp/mysql-mailcow 1>&2; err_count=$(( ${err_count} + $? )) ++ /usr/lib/nagios/plugins/check_mysql_query -f /etc/my.cnf.d/client.cnf -s /var/run/mysqld/mysqld.sock -u ${DBUSER} -p ${DBPASS} -d ${DBNAME} -q "SELECT COUNT(*) FROM information_schema.tables" 2>> /tmp/mysql-mailcow 1>&2; err_count=$(( ${err_count} + $? )) + [ ${err_c_cur} -eq ${err_count} ] && [ ! $((${err_count} - 1)) -lt 0 ] && err_count=$((${err_count} - 1)) diff_c=1 + [ ${err_c_cur} -ne ${err_count} ] && diff_c=$(( ${err_c_cur} - ${err_count} )) + progress "MySQL/MariaDB" ${THRESHOLD} $(( ${THRESHOLD} - ${err_count} )) ${diff_c} +@@ -384,7 +384,7 @@ mysql_repl_checks() { + while [ ${err_count} -lt ${THRESHOLD} ]; do + touch /tmp/mysql_repl_checks; echo "$(tail -50 /tmp/mysql_repl_checks)" > /tmp/mysql_repl_checks + err_c_cur=${err_count} +- /usr/lib/nagios/plugins/check_mysql_slavestatus.sh -S /var/run/mysqld/mysqld.sock -u root -p ${DBROOT} 2>> /tmp/mysql_repl_checks 1>&2; err_count=$(( ${err_count} + $? )) ++ /usr/lib/nagios/plugins/check_mysql_slavestatus.sh -o /etc/my.cnf.d/client.cnf -S /var/run/mysqld/mysqld.sock -u root -p ${DBROOT} 2>> /tmp/mysql_repl_checks 1>&2; err_count=$(( ${err_count} + $? )) + [ ${err_c_cur} -eq ${err_count} ] && [ ! $((${err_count} - 1)) -lt 0 ] && err_count=$((${err_count} - 1)) diff_c=1 + [ ${err_c_cur} -ne ${err_count} ] && diff_c=$(( ${err_c_cur} - ${err_count} )) + progress "MySQL/MariaDB replication" ${THRESHOLD} $(( ${THRESHOLD} - ${err_count} )) ${diff_c} +diff --git a/docker-compose.yml b/docker-compose.yml +index fbf1125f..1d77b9b8 100644 +--- a/docker-compose.yml ++++ b/docker-compose.yml +@@ -526,7 +526,7 @@ services: + - /lib/modules:/lib/modules:ro + + watchdog-mailcow: +- image: ghcr.io/mailcow/watchdog:2.10 ++ image: ghcr.io/mailcow/watchdog:2.11 + dns: + - ${IPV4_NETWORK:-172.22.1}.254 + tmpfs: diff --git a/tasks/mailcow__mailcow-dockerized-7103/tests/test.sh b/tasks/mailcow__mailcow-dockerized-7103/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..0d88acb6b6ebc070fadfb07ce93700878b083090 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7103/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 8f883f3d374b4de9b3ad731d3bef5d667b095ae8 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/mailcow__mailcow-dockerized-7103/tests/verifier.py b/tasks/mailcow__mailcow-dockerized-7103/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7103/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/mailcow__mailcow-dockerized-7104/environment/Dockerfile b/tasks/mailcow__mailcow-dockerized-7104/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..3a9e27fa1a3f1cb955df1b9f112dc580108bc601 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7104/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/mailcow/mailcow-dockerized.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/mailcow/mailcow-dockerized.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/mailcow/mailcow-dockerized.git +WORKDIR /workspace +RUN git fetch --depth 1 origin b84ba8ded12fc5646a634cf8d39f8a5c9b298088 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard b84ba8ded12fc5646a634cf8d39f8a5c9b298088 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base b84ba8ded12fc5646a634cf8d39f8a5c9b298088 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/mailcow__mailcow-dockerized-7104/instruction.md b/tasks/mailcow__mailcow-dockerized-7104/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0924cde2a96f05ff3c45fe8c22aa9856894dc2f0 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7104/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Hotfix 2026-03 + +## Description + +Hotfix 2026-03 + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `b84ba8ded12f`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/mailcow__mailcow-dockerized-7104/solution/patch.diff b/tasks/mailcow__mailcow-dockerized-7104/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..8ed7ed881d0185647f1b04daf15c44811e904c0b --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7104/solution/patch.diff @@ -0,0 +1,66 @@ +diff --git a/data/Dockerfiles/watchdog/Dockerfile b/data/Dockerfiles/watchdog/Dockerfile +index 83108673..54854ea1 100644 +--- a/data/Dockerfiles/watchdog/Dockerfile ++++ b/data/Dockerfiles/watchdog/Dockerfile +@@ -37,5 +37,6 @@ RUN apk add --update \ + COPY watchdog.sh /watchdog.sh + COPY check_mysql_slavestatus.sh /usr/lib/nagios/plugins/check_mysql_slavestatus.sh + COPY check_dns.sh /usr/lib/mailcow/check_dns.sh ++COPY client.cnf /etc/my.cnf.d/client.cnf + + CMD ["/watchdog.sh"] +diff --git a/data/Dockerfiles/watchdog/client.cnf b/data/Dockerfiles/watchdog/client.cnf +new file mode 100644 +index 00000000..f078f3cb +--- /dev/null ++++ b/data/Dockerfiles/watchdog/client.cnf +@@ -0,0 +1,3 @@ ++[client] ++ssl = false ++ssl-verify-server-cert = false +diff --git a/data/Dockerfiles/watchdog/watchdog.sh b/data/Dockerfiles/watchdog/watchdog.sh +index 558aaa19..020f3f83 100755 +--- a/data/Dockerfiles/watchdog/watchdog.sh ++++ b/data/Dockerfiles/watchdog/watchdog.sh +@@ -38,7 +38,7 @@ if [[ ! -p /tmp/com_pipe ]]; then + fi + + # Wait for containers +-while ! mariadb-admin status --ssl=false --socket=/var/run/mysqld/mysqld.sock -u${DBUSER} -p${DBPASS} --silent; do ++while ! mariadb-admin status --skip-ssl --socket=/var/run/mysqld/mysqld.sock -u${DBUSER} -p${DBPASS} --silent; do + echo "Waiting for SQL..." + sleep 2 + done +@@ -359,8 +359,8 @@ mysql_checks() { + while [ ${err_count} -lt ${THRESHOLD} ]; do + touch /tmp/mysql-mailcow; echo "$(tail -50 /tmp/mysql-mailcow)" > /tmp/mysql-mailcow + err_c_cur=${err_count} +- /usr/lib/nagios/plugins/check_mysql -s /var/run/mysqld/mysqld.sock -u ${DBUSER} -p ${DBPASS} -d ${DBNAME} 2>> /tmp/mysql-mailcow 1>&2; err_count=$(( ${err_count} + $? )) +- /usr/lib/nagios/plugins/check_mysql_query -s /var/run/mysqld/mysqld.sock -u ${DBUSER} -p ${DBPASS} -d ${DBNAME} -q "SELECT COUNT(*) FROM information_schema.tables" 2>> /tmp/mysql-mailcow 1>&2; err_count=$(( ${err_count} + $? )) ++ /usr/lib/nagios/plugins/check_mysql -f /etc/my.cnf.d/client.cnf -s /var/run/mysqld/mysqld.sock -u ${DBUSER} -p ${DBPASS} -d ${DBNAME} 2>> /tmp/mysql-mailcow 1>&2; err_count=$(( ${err_count} + $? )) ++ /usr/lib/nagios/plugins/check_mysql_query -f /etc/my.cnf.d/client.cnf -s /var/run/mysqld/mysqld.sock -u ${DBUSER} -p ${DBPASS} -d ${DBNAME} -q "SELECT COUNT(*) FROM information_schema.tables" 2>> /tmp/mysql-mailcow 1>&2; err_count=$(( ${err_count} + $? )) + [ ${err_c_cur} -eq ${err_count} ] && [ ! $((${err_count} - 1)) -lt 0 ] && err_count=$((${err_count} - 1)) diff_c=1 + [ ${err_c_cur} -ne ${err_count} ] && diff_c=$(( ${err_c_cur} - ${err_count} )) + progress "MySQL/MariaDB" ${THRESHOLD} $(( ${THRESHOLD} - ${err_count} )) ${diff_c} +@@ -384,7 +384,7 @@ mysql_repl_checks() { + while [ ${err_count} -lt ${THRESHOLD} ]; do + touch /tmp/mysql_repl_checks; echo "$(tail -50 /tmp/mysql_repl_checks)" > /tmp/mysql_repl_checks + err_c_cur=${err_count} +- /usr/lib/nagios/plugins/check_mysql_slavestatus.sh -S /var/run/mysqld/mysqld.sock -u root -p ${DBROOT} 2>> /tmp/mysql_repl_checks 1>&2; err_count=$(( ${err_count} + $? )) ++ /usr/lib/nagios/plugins/check_mysql_slavestatus.sh -o /etc/my.cnf.d/client.cnf -S /var/run/mysqld/mysqld.sock -u root -p ${DBROOT} 2>> /tmp/mysql_repl_checks 1>&2; err_count=$(( ${err_count} + $? )) + [ ${err_c_cur} -eq ${err_count} ] && [ ! $((${err_count} - 1)) -lt 0 ] && err_count=$((${err_count} - 1)) diff_c=1 + [ ${err_c_cur} -ne ${err_count} ] && diff_c=$(( ${err_c_cur} - ${err_count} )) + progress "MySQL/MariaDB replication" ${THRESHOLD} $(( ${THRESHOLD} - ${err_count} )) ${diff_c} +diff --git a/docker-compose.yml b/docker-compose.yml +index fbf1125f..1d77b9b8 100644 +--- a/docker-compose.yml ++++ b/docker-compose.yml +@@ -526,7 +526,7 @@ services: + - /lib/modules:/lib/modules:ro + + watchdog-mailcow: +- image: ghcr.io/mailcow/watchdog:2.10 ++ image: ghcr.io/mailcow/watchdog:2.11 + dns: + - ${IPV4_NETWORK:-172.22.1}.254 + tmpfs: diff --git a/tasks/mailcow__mailcow-dockerized-7104/solution/solve.sh b/tasks/mailcow__mailcow-dockerized-7104/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7104/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/mailcow__mailcow-dockerized-7104/task.toml b/tasks/mailcow__mailcow-dockerized-7104/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..0f1b16dc36fd67f3a987daf912364fd40f767ae4 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7104/task.toml @@ -0,0 +1,71 @@ +version = "1.0" + +[task] +name = "trending/mailcow__mailcow-dockerized-7104" +description = "Hotfix 2026-03" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "mailcow-dockerized", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "mailcow/mailcow-dockerized" +ref = "b84ba8ded12fc5646a634cf8d39f8a5c9b298088" +reference = "https://github.com/mailcow/mailcow-dockerized/pull/7104" +source_access = "auto" +built_at = "2026-11-16T16:09:53.232956+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:acd67c93e879063b8d102f37ff3813b8e270b5d2321bc3bb2bf4809d3ee436f2" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-03-10T09:05:40Z" +diff_format = "unified" +context_files = [ + "data/Dockerfiles/watchdog/Dockerfile", + "data/Dockerfiles/watchdog/client.cnf", + "data/Dockerfiles/watchdog/watchdog.sh", + "docker-compose.yml", +] +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.443587+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:8140a4c781063c592c10906ae17fb3cd158bf886b0a577c262d43131a9d891b2" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/mailcow__mailcow-dockerized-7104/tests/capture.py b/tasks/mailcow__mailcow-dockerized-7104/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7104/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/mailcow__mailcow-dockerized-7104/tests/instruction.md b/tasks/mailcow__mailcow-dockerized-7104/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0924cde2a96f05ff3c45fe8c22aa9856894dc2f0 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7104/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Hotfix 2026-03 + +## Description + +Hotfix 2026-03 + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `b84ba8ded12f`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/mailcow__mailcow-dockerized-7104/tests/oracle.patch b/tasks/mailcow__mailcow-dockerized-7104/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..8ed7ed881d0185647f1b04daf15c44811e904c0b --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7104/tests/oracle.patch @@ -0,0 +1,66 @@ +diff --git a/data/Dockerfiles/watchdog/Dockerfile b/data/Dockerfiles/watchdog/Dockerfile +index 83108673..54854ea1 100644 +--- a/data/Dockerfiles/watchdog/Dockerfile ++++ b/data/Dockerfiles/watchdog/Dockerfile +@@ -37,5 +37,6 @@ RUN apk add --update \ + COPY watchdog.sh /watchdog.sh + COPY check_mysql_slavestatus.sh /usr/lib/nagios/plugins/check_mysql_slavestatus.sh + COPY check_dns.sh /usr/lib/mailcow/check_dns.sh ++COPY client.cnf /etc/my.cnf.d/client.cnf + + CMD ["/watchdog.sh"] +diff --git a/data/Dockerfiles/watchdog/client.cnf b/data/Dockerfiles/watchdog/client.cnf +new file mode 100644 +index 00000000..f078f3cb +--- /dev/null ++++ b/data/Dockerfiles/watchdog/client.cnf +@@ -0,0 +1,3 @@ ++[client] ++ssl = false ++ssl-verify-server-cert = false +diff --git a/data/Dockerfiles/watchdog/watchdog.sh b/data/Dockerfiles/watchdog/watchdog.sh +index 558aaa19..020f3f83 100755 +--- a/data/Dockerfiles/watchdog/watchdog.sh ++++ b/data/Dockerfiles/watchdog/watchdog.sh +@@ -38,7 +38,7 @@ if [[ ! -p /tmp/com_pipe ]]; then + fi + + # Wait for containers +-while ! mariadb-admin status --ssl=false --socket=/var/run/mysqld/mysqld.sock -u${DBUSER} -p${DBPASS} --silent; do ++while ! mariadb-admin status --skip-ssl --socket=/var/run/mysqld/mysqld.sock -u${DBUSER} -p${DBPASS} --silent; do + echo "Waiting for SQL..." + sleep 2 + done +@@ -359,8 +359,8 @@ mysql_checks() { + while [ ${err_count} -lt ${THRESHOLD} ]; do + touch /tmp/mysql-mailcow; echo "$(tail -50 /tmp/mysql-mailcow)" > /tmp/mysql-mailcow + err_c_cur=${err_count} +- /usr/lib/nagios/plugins/check_mysql -s /var/run/mysqld/mysqld.sock -u ${DBUSER} -p ${DBPASS} -d ${DBNAME} 2>> /tmp/mysql-mailcow 1>&2; err_count=$(( ${err_count} + $? )) +- /usr/lib/nagios/plugins/check_mysql_query -s /var/run/mysqld/mysqld.sock -u ${DBUSER} -p ${DBPASS} -d ${DBNAME} -q "SELECT COUNT(*) FROM information_schema.tables" 2>> /tmp/mysql-mailcow 1>&2; err_count=$(( ${err_count} + $? )) ++ /usr/lib/nagios/plugins/check_mysql -f /etc/my.cnf.d/client.cnf -s /var/run/mysqld/mysqld.sock -u ${DBUSER} -p ${DBPASS} -d ${DBNAME} 2>> /tmp/mysql-mailcow 1>&2; err_count=$(( ${err_count} + $? )) ++ /usr/lib/nagios/plugins/check_mysql_query -f /etc/my.cnf.d/client.cnf -s /var/run/mysqld/mysqld.sock -u ${DBUSER} -p ${DBPASS} -d ${DBNAME} -q "SELECT COUNT(*) FROM information_schema.tables" 2>> /tmp/mysql-mailcow 1>&2; err_count=$(( ${err_count} + $? )) + [ ${err_c_cur} -eq ${err_count} ] && [ ! $((${err_count} - 1)) -lt 0 ] && err_count=$((${err_count} - 1)) diff_c=1 + [ ${err_c_cur} -ne ${err_count} ] && diff_c=$(( ${err_c_cur} - ${err_count} )) + progress "MySQL/MariaDB" ${THRESHOLD} $(( ${THRESHOLD} - ${err_count} )) ${diff_c} +@@ -384,7 +384,7 @@ mysql_repl_checks() { + while [ ${err_count} -lt ${THRESHOLD} ]; do + touch /tmp/mysql_repl_checks; echo "$(tail -50 /tmp/mysql_repl_checks)" > /tmp/mysql_repl_checks + err_c_cur=${err_count} +- /usr/lib/nagios/plugins/check_mysql_slavestatus.sh -S /var/run/mysqld/mysqld.sock -u root -p ${DBROOT} 2>> /tmp/mysql_repl_checks 1>&2; err_count=$(( ${err_count} + $? )) ++ /usr/lib/nagios/plugins/check_mysql_slavestatus.sh -o /etc/my.cnf.d/client.cnf -S /var/run/mysqld/mysqld.sock -u root -p ${DBROOT} 2>> /tmp/mysql_repl_checks 1>&2; err_count=$(( ${err_count} + $? )) + [ ${err_c_cur} -eq ${err_count} ] && [ ! $((${err_count} - 1)) -lt 0 ] && err_count=$((${err_count} - 1)) diff_c=1 + [ ${err_c_cur} -ne ${err_count} ] && diff_c=$(( ${err_c_cur} - ${err_count} )) + progress "MySQL/MariaDB replication" ${THRESHOLD} $(( ${THRESHOLD} - ${err_count} )) ${diff_c} +diff --git a/docker-compose.yml b/docker-compose.yml +index fbf1125f..1d77b9b8 100644 +--- a/docker-compose.yml ++++ b/docker-compose.yml +@@ -526,7 +526,7 @@ services: + - /lib/modules:/lib/modules:ro + + watchdog-mailcow: +- image: ghcr.io/mailcow/watchdog:2.10 ++ image: ghcr.io/mailcow/watchdog:2.11 + dns: + - ${IPV4_NETWORK:-172.22.1}.254 + tmpfs: diff --git a/tasks/mailcow__mailcow-dockerized-7104/tests/test.sh b/tasks/mailcow__mailcow-dockerized-7104/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..a46a7e7cdb86c6df73f63b9ec2251fe298f3c65a --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7104/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace b84ba8ded12fc5646a634cf8d39f8a5c9b298088 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/mailcow__mailcow-dockerized-7104/tests/verifier.py b/tasks/mailcow__mailcow-dockerized-7104/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7104/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/mailcow__mailcow-dockerized-7108/environment/Dockerfile b/tasks/mailcow__mailcow-dockerized-7108/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..463b516570e2ad977b6f146a06f234b6bb6a7d35 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7108/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/mailcow/mailcow-dockerized.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/mailcow/mailcow-dockerized.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/mailcow/mailcow-dockerized.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 5888e248c39c21b70ee50db6b12cd18e00c755ee 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 5888e248c39c21b70ee50db6b12cd18e00c755ee \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 5888e248c39c21b70ee50db6b12cd18e00c755ee \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/mailcow__mailcow-dockerized-7108/instruction.md b/tasks/mailcow__mailcow-dockerized-7108/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e0158e42dbefbeb4284b333acc6414e69979c495 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7108/instruction.md @@ -0,0 +1,34 @@ +# Issue + +**Title:** [SOGo] Fix draft folder creation by adding /var/spool/sogo directory + +## Description + + + +## Contribution Guidelines + +* [x] I've read the [contribution guidelines](https://github.com/mailcow/mailcow-dockerized/blob/master/CONTRIBUTING.md) and wholeheartedly agree them + + + +## What does this PR include? + +### Short Description + +Fixes draft folder creation failures in SOGo by adding the missing `/var/spool/sogo` directory. + +After updating to the self-compiled SOGo build, users reported errors when trying to create draft messages: `could not create folder for draft: '/var/spool/sogo/name@domain.tld/newDraft...'`. The issue was caused by the `/var/spool/sogo` directory not being created during the image build process. + +This PR adds `/var/spool/sogo` to the directory creation and ownership setup in the SOGo Dockerfile. + +Fixes: +- #7105 + +### Affected Containers + +- sogo-mailcow + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `5888e248c39c`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/mailcow__mailcow-dockerized-7108/solution/patch.diff b/tasks/mailcow__mailcow-dockerized-7108/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..f1e5f249427658520859858f24ddecd7faf32619 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7108/solution/patch.diff @@ -0,0 +1,28 @@ +diff --git a/data/Dockerfiles/sogo/Dockerfile b/data/Dockerfiles/sogo/Dockerfile +index d118b649..5d83c4eb 100644 +--- a/data/Dockerfiles/sogo/Dockerfile ++++ b/data/Dockerfiles/sogo/Dockerfile +@@ -146,8 +146,8 @@ RUN echo "/usr/lib64" > /etc/ld.so.conf.d/sogo.conf \ + # Create sogo user and group + RUN groupadd -r -g 999 sogo \ + && useradd -r -u 999 -g sogo -d /var/lib/sogo -s /bin/bash -c "SOGo Daemon" sogo \ +- && mkdir -p /var/lib/sogo /var/run/sogo /var/log/sogo \ +- && chown -R sogo:sogo /var/lib/sogo /var/run/sogo /var/log/sogo ++ && mkdir -p /var/lib/sogo /var/run/sogo /var/log/sogo /var/spool/sogo \ ++ && chown -R sogo:sogo /var/lib/sogo /var/run/sogo /var/log/sogo /var/spool/sogo + + # Create symlinks for SOGo binaries + RUN ln -s /usr/local/sbin/sogod /usr/sbin/sogod \ +diff --git a/docker-compose.yml b/docker-compose.yml +index 1d77b9b8..82c14749 100644 +--- a/docker-compose.yml ++++ b/docker-compose.yml +@@ -200,7 +200,7 @@ services: + - phpfpm + + sogo-mailcow: +- image: ghcr.io/mailcow/sogo:5.12.5-1 ++ image: ghcr.io/mailcow/sogo:5.12.5-2 + environment: + - DBNAME=${DBNAME} + - DBUSER=${DBUSER} diff --git a/tasks/mailcow__mailcow-dockerized-7108/solution/solve.sh b/tasks/mailcow__mailcow-dockerized-7108/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7108/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/mailcow__mailcow-dockerized-7108/task.toml b/tasks/mailcow__mailcow-dockerized-7108/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..592de8138beb3b8f2425e0fcb3fdfb8056dcd115 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7108/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/mailcow__mailcow-dockerized-7108" +description = "[SOGo] Fix draft folder creation by adding /var/spool/sogo directory" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "mailcow-dockerized", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "mailcow/mailcow-dockerized" +ref = "5888e248c39c21b70ee50db6b12cd18e00c755ee" +reference = "https://github.com/mailcow/mailcow-dockerized/pull/7108" +source_access = "auto" +built_at = "2026-11-16T16:09:53.223024+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:ca559fc23026a14ebcdb1b5fba74a78603cbbe1bd588d8ee841a027297a5b169" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-03-10T09:38:50Z" +diff_format = "unified" +context_files = [ + "data/Dockerfiles/sogo/Dockerfile", + "docker-compose.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.444058+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:3f9011528f124cce9d953682c51866b98e82b70741532554170468c00abd0e3a" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/mailcow__mailcow-dockerized-7108/tests/capture.py b/tasks/mailcow__mailcow-dockerized-7108/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7108/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/mailcow__mailcow-dockerized-7108/tests/instruction.md b/tasks/mailcow__mailcow-dockerized-7108/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e0158e42dbefbeb4284b333acc6414e69979c495 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7108/tests/instruction.md @@ -0,0 +1,34 @@ +# Issue + +**Title:** [SOGo] Fix draft folder creation by adding /var/spool/sogo directory + +## Description + + + +## Contribution Guidelines + +* [x] I've read the [contribution guidelines](https://github.com/mailcow/mailcow-dockerized/blob/master/CONTRIBUTING.md) and wholeheartedly agree them + + + +## What does this PR include? + +### Short Description + +Fixes draft folder creation failures in SOGo by adding the missing `/var/spool/sogo` directory. + +After updating to the self-compiled SOGo build, users reported errors when trying to create draft messages: `could not create folder for draft: '/var/spool/sogo/name@domain.tld/newDraft...'`. The issue was caused by the `/var/spool/sogo` directory not being created during the image build process. + +This PR adds `/var/spool/sogo` to the directory creation and ownership setup in the SOGo Dockerfile. + +Fixes: +- #7105 + +### Affected Containers + +- sogo-mailcow + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `5888e248c39c`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/mailcow__mailcow-dockerized-7108/tests/oracle.patch b/tasks/mailcow__mailcow-dockerized-7108/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..f1e5f249427658520859858f24ddecd7faf32619 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7108/tests/oracle.patch @@ -0,0 +1,28 @@ +diff --git a/data/Dockerfiles/sogo/Dockerfile b/data/Dockerfiles/sogo/Dockerfile +index d118b649..5d83c4eb 100644 +--- a/data/Dockerfiles/sogo/Dockerfile ++++ b/data/Dockerfiles/sogo/Dockerfile +@@ -146,8 +146,8 @@ RUN echo "/usr/lib64" > /etc/ld.so.conf.d/sogo.conf \ + # Create sogo user and group + RUN groupadd -r -g 999 sogo \ + && useradd -r -u 999 -g sogo -d /var/lib/sogo -s /bin/bash -c "SOGo Daemon" sogo \ +- && mkdir -p /var/lib/sogo /var/run/sogo /var/log/sogo \ +- && chown -R sogo:sogo /var/lib/sogo /var/run/sogo /var/log/sogo ++ && mkdir -p /var/lib/sogo /var/run/sogo /var/log/sogo /var/spool/sogo \ ++ && chown -R sogo:sogo /var/lib/sogo /var/run/sogo /var/log/sogo /var/spool/sogo + + # Create symlinks for SOGo binaries + RUN ln -s /usr/local/sbin/sogod /usr/sbin/sogod \ +diff --git a/docker-compose.yml b/docker-compose.yml +index 1d77b9b8..82c14749 100644 +--- a/docker-compose.yml ++++ b/docker-compose.yml +@@ -200,7 +200,7 @@ services: + - phpfpm + + sogo-mailcow: +- image: ghcr.io/mailcow/sogo:5.12.5-1 ++ image: ghcr.io/mailcow/sogo:5.12.5-2 + environment: + - DBNAME=${DBNAME} + - DBUSER=${DBUSER} diff --git a/tasks/mailcow__mailcow-dockerized-7108/tests/test.sh b/tasks/mailcow__mailcow-dockerized-7108/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3940322b566840be9d0f61f76575cfd3a432d86b --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7108/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 5888e248c39c21b70ee50db6b12cd18e00c755ee > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/mailcow__mailcow-dockerized-7108/tests/verifier.py b/tasks/mailcow__mailcow-dockerized-7108/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7108/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/mailcow__mailcow-dockerized-7109/environment/Dockerfile b/tasks/mailcow__mailcow-dockerized-7109/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..dfbb4e79833bb1e1d0cc82bf7bd62c5343b7b246 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7109/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/mailcow/mailcow-dockerized.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/mailcow/mailcow-dockerized.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/mailcow/mailcow-dockerized.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 7515bef66cc004f431e665c90b22a8bd0296ba93 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 7515bef66cc004f431e665c90b22a8bd0296ba93 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 7515bef66cc004f431e665c90b22a8bd0296ba93 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/mailcow__mailcow-dockerized-7109/instruction.md b/tasks/mailcow__mailcow-dockerized-7109/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..338c89f99111278198a26bec1bcea37f0b7ea327 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7109/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Hotfix 2026-03 + +## Description + +Hotfix 2026-03 + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `7515bef66cc0`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/mailcow__mailcow-dockerized-7109/solution/patch.diff b/tasks/mailcow__mailcow-dockerized-7109/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..f1e5f249427658520859858f24ddecd7faf32619 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7109/solution/patch.diff @@ -0,0 +1,28 @@ +diff --git a/data/Dockerfiles/sogo/Dockerfile b/data/Dockerfiles/sogo/Dockerfile +index d118b649..5d83c4eb 100644 +--- a/data/Dockerfiles/sogo/Dockerfile ++++ b/data/Dockerfiles/sogo/Dockerfile +@@ -146,8 +146,8 @@ RUN echo "/usr/lib64" > /etc/ld.so.conf.d/sogo.conf \ + # Create sogo user and group + RUN groupadd -r -g 999 sogo \ + && useradd -r -u 999 -g sogo -d /var/lib/sogo -s /bin/bash -c "SOGo Daemon" sogo \ +- && mkdir -p /var/lib/sogo /var/run/sogo /var/log/sogo \ +- && chown -R sogo:sogo /var/lib/sogo /var/run/sogo /var/log/sogo ++ && mkdir -p /var/lib/sogo /var/run/sogo /var/log/sogo /var/spool/sogo \ ++ && chown -R sogo:sogo /var/lib/sogo /var/run/sogo /var/log/sogo /var/spool/sogo + + # Create symlinks for SOGo binaries + RUN ln -s /usr/local/sbin/sogod /usr/sbin/sogod \ +diff --git a/docker-compose.yml b/docker-compose.yml +index 1d77b9b8..82c14749 100644 +--- a/docker-compose.yml ++++ b/docker-compose.yml +@@ -200,7 +200,7 @@ services: + - phpfpm + + sogo-mailcow: +- image: ghcr.io/mailcow/sogo:5.12.5-1 ++ image: ghcr.io/mailcow/sogo:5.12.5-2 + environment: + - DBNAME=${DBNAME} + - DBUSER=${DBUSER} diff --git a/tasks/mailcow__mailcow-dockerized-7109/solution/solve.sh b/tasks/mailcow__mailcow-dockerized-7109/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7109/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/mailcow__mailcow-dockerized-7109/task.toml b/tasks/mailcow__mailcow-dockerized-7109/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..e5553eda626d3672d7838defa5a9a6961954963b --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7109/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/mailcow__mailcow-dockerized-7109" +description = "Hotfix 2026-03" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "mailcow-dockerized", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "mailcow/mailcow-dockerized" +ref = "7515bef66cc004f431e665c90b22a8bd0296ba93" +reference = "https://github.com/mailcow/mailcow-dockerized/pull/7109" +source_access = "auto" +built_at = "2026-11-16T16:09:53.231681+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:96cda18d49e3b8ffb177448d99d9785f08fe65c623e5e2a3b876e821d711f6fc" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-03-10T09:39:43Z" +diff_format = "unified" +context_files = [ + "data/Dockerfiles/sogo/Dockerfile", + "docker-compose.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.444535+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:8e30cb78f08b2646a284cce43678e74d5784d3a7a6a0dad88b22553b89e36e61" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/mailcow__mailcow-dockerized-7109/tests/capture.py b/tasks/mailcow__mailcow-dockerized-7109/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7109/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/mailcow__mailcow-dockerized-7109/tests/instruction.md b/tasks/mailcow__mailcow-dockerized-7109/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..338c89f99111278198a26bec1bcea37f0b7ea327 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7109/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Hotfix 2026-03 + +## Description + +Hotfix 2026-03 + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `7515bef66cc0`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/mailcow__mailcow-dockerized-7109/tests/oracle.patch b/tasks/mailcow__mailcow-dockerized-7109/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..f1e5f249427658520859858f24ddecd7faf32619 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7109/tests/oracle.patch @@ -0,0 +1,28 @@ +diff --git a/data/Dockerfiles/sogo/Dockerfile b/data/Dockerfiles/sogo/Dockerfile +index d118b649..5d83c4eb 100644 +--- a/data/Dockerfiles/sogo/Dockerfile ++++ b/data/Dockerfiles/sogo/Dockerfile +@@ -146,8 +146,8 @@ RUN echo "/usr/lib64" > /etc/ld.so.conf.d/sogo.conf \ + # Create sogo user and group + RUN groupadd -r -g 999 sogo \ + && useradd -r -u 999 -g sogo -d /var/lib/sogo -s /bin/bash -c "SOGo Daemon" sogo \ +- && mkdir -p /var/lib/sogo /var/run/sogo /var/log/sogo \ +- && chown -R sogo:sogo /var/lib/sogo /var/run/sogo /var/log/sogo ++ && mkdir -p /var/lib/sogo /var/run/sogo /var/log/sogo /var/spool/sogo \ ++ && chown -R sogo:sogo /var/lib/sogo /var/run/sogo /var/log/sogo /var/spool/sogo + + # Create symlinks for SOGo binaries + RUN ln -s /usr/local/sbin/sogod /usr/sbin/sogod \ +diff --git a/docker-compose.yml b/docker-compose.yml +index 1d77b9b8..82c14749 100644 +--- a/docker-compose.yml ++++ b/docker-compose.yml +@@ -200,7 +200,7 @@ services: + - phpfpm + + sogo-mailcow: +- image: ghcr.io/mailcow/sogo:5.12.5-1 ++ image: ghcr.io/mailcow/sogo:5.12.5-2 + environment: + - DBNAME=${DBNAME} + - DBUSER=${DBUSER} diff --git a/tasks/mailcow__mailcow-dockerized-7109/tests/test.sh b/tasks/mailcow__mailcow-dockerized-7109/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..09a2c76cf6c63cf17ecb7aaace97d10a41db229c --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7109/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 7515bef66cc004f431e665c90b22a8bd0296ba93 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/mailcow__mailcow-dockerized-7109/tests/verifier.py b/tasks/mailcow__mailcow-dockerized-7109/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7109/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/mailcow__mailcow-dockerized-7111/environment/Dockerfile b/tasks/mailcow__mailcow-dockerized-7111/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..3665a807d240ccc1c278daf637b558833f3ade8a --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7111/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/mailcow/mailcow-dockerized.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/mailcow/mailcow-dockerized.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/mailcow/mailcow-dockerized.git +WORKDIR /workspace +RUN git fetch --depth 1 origin bea9ad7e8f09186bddd3e9b8cdba0d384417bd11 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard bea9ad7e8f09186bddd3e9b8cdba0d384417bd11 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base bea9ad7e8f09186bddd3e9b8cdba0d384417bd11 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/mailcow__mailcow-dockerized-7111/instruction.md b/tasks/mailcow__mailcow-dockerized-7111/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..16811eb86940413e137304d3d618b08950e74462 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7111/instruction.md @@ -0,0 +1,32 @@ +# Issue + +**Title:** [SOGo] Add ActiveSync support + +## Description + + + +## Contribution Guidelines + +* [x] I've read the [contribution guidelines](https://github.com/mailcow/mailcow-dockerized/blob/master/CONTRIBUTING.md) and wholeheartedly agree them + + + +## What does this PR include? + +### Short Description + +Adds Microsoft ActiveSync support to the self-compiled SOGo build. The ActiveSync module was not being built due to missing build dependencies (pkg-config and libwbxml2), causing mobile device synchronization via Exchange ActiveSync protocol to fail. + +This fix ensures the ActiveSync.SOGo bundle is properly compiled and installed, enabling full ActiveSync protocol support + +Fixes: +- #7110 + +### Affected Containers + +- sogo-mailcow + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `bea9ad7e8f09`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/mailcow__mailcow-dockerized-7111/solution/patch.diff b/tasks/mailcow__mailcow-dockerized-7111/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..8bfe53b4ca5843da0b31b7c64a7ab83fa4000353 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7111/solution/patch.diff @@ -0,0 +1,51 @@ +diff --git a/data/Dockerfiles/sogo/Dockerfile b/data/Dockerfiles/sogo/Dockerfile +index 5d83c4eb..96d2e0a4 100644 +--- a/data/Dockerfiles/sogo/Dockerfile ++++ b/data/Dockerfiles/sogo/Dockerfile +@@ -26,6 +26,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ + git \ + build-essential \ + gobjc \ ++ pkg-config \ + gnustep-make \ + gnustep-base-runtime \ + libgnustep-base-dev \ +@@ -40,6 +41,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ + libcurl4-openssl-dev \ + libzip-dev \ + libytnef0-dev \ ++ libwbxml2-dev \ + curl \ + ca-certificates \ + # Runtime dependencies +@@ -68,6 +70,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ + libcurl4 \ + libzip4 \ + libytnef0 \ ++ libwbxml2-1 \ + # Download gosu + && dpkgArch="$(dpkg --print-architecture | awk -F- '{ print $NF }')" \ + && wget -O /usr/local/bin/gosu "https://github.com/tianon/gosu/releases/download/$GOSU_VERSION/gosu-$dpkgArch" \ +@@ -97,6 +100,9 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ + && ./configure --disable-debug --disable-strip \ + && make -j$(nproc) \ + && make install \ ++ && cd /tmp/sogo/ActiveSync \ ++ && . /usr/share/GNUstep/Makefiles/GNUstep.sh \ ++ && make -j$(nproc) install \ + && cd / \ + && rm -rf /tmp/sogo \ + # Strip binaries +diff --git a/docker-compose.yml b/docker-compose.yml +index 82c14749..98dccea5 100644 +--- a/docker-compose.yml ++++ b/docker-compose.yml +@@ -200,7 +200,7 @@ services: + - phpfpm + + sogo-mailcow: +- image: ghcr.io/mailcow/sogo:5.12.5-2 ++ image: ghcr.io/mailcow/sogo:5.12.5-3 + environment: + - DBNAME=${DBNAME} + - DBUSER=${DBUSER} diff --git a/tasks/mailcow__mailcow-dockerized-7111/solution/solve.sh b/tasks/mailcow__mailcow-dockerized-7111/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7111/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/mailcow__mailcow-dockerized-7111/task.toml b/tasks/mailcow__mailcow-dockerized-7111/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..d9db430909abe38914def9979a4edcdc791af373 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7111/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/mailcow__mailcow-dockerized-7111" +description = "[SOGo] Add ActiveSync support" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "mailcow-dockerized", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "mailcow/mailcow-dockerized" +ref = "bea9ad7e8f09186bddd3e9b8cdba0d384417bd11" +reference = "https://github.com/mailcow/mailcow-dockerized/pull/7111" +source_access = "auto" +built_at = "2026-11-16T16:09:53.224504+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:7d3fa2acb4f74ba5ecc70bcd88caa2875b87d0bb8c7bf98316e29732555aab6f" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-03-10T12:37:59Z" +diff_format = "unified" +context_files = [ + "data/Dockerfiles/sogo/Dockerfile", + "docker-compose.yml", +] +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.445024+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:8acbbd2b55b17b3d589c7ad1799988b961fdae143cda79eef4c9222533277c4d" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/mailcow__mailcow-dockerized-7111/tests/capture.py b/tasks/mailcow__mailcow-dockerized-7111/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7111/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/mailcow__mailcow-dockerized-7111/tests/instruction.md b/tasks/mailcow__mailcow-dockerized-7111/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..16811eb86940413e137304d3d618b08950e74462 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7111/tests/instruction.md @@ -0,0 +1,32 @@ +# Issue + +**Title:** [SOGo] Add ActiveSync support + +## Description + + + +## Contribution Guidelines + +* [x] I've read the [contribution guidelines](https://github.com/mailcow/mailcow-dockerized/blob/master/CONTRIBUTING.md) and wholeheartedly agree them + + + +## What does this PR include? + +### Short Description + +Adds Microsoft ActiveSync support to the self-compiled SOGo build. The ActiveSync module was not being built due to missing build dependencies (pkg-config and libwbxml2), causing mobile device synchronization via Exchange ActiveSync protocol to fail. + +This fix ensures the ActiveSync.SOGo bundle is properly compiled and installed, enabling full ActiveSync protocol support + +Fixes: +- #7110 + +### Affected Containers + +- sogo-mailcow + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `bea9ad7e8f09`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/mailcow__mailcow-dockerized-7111/tests/oracle.patch b/tasks/mailcow__mailcow-dockerized-7111/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..8bfe53b4ca5843da0b31b7c64a7ab83fa4000353 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7111/tests/oracle.patch @@ -0,0 +1,51 @@ +diff --git a/data/Dockerfiles/sogo/Dockerfile b/data/Dockerfiles/sogo/Dockerfile +index 5d83c4eb..96d2e0a4 100644 +--- a/data/Dockerfiles/sogo/Dockerfile ++++ b/data/Dockerfiles/sogo/Dockerfile +@@ -26,6 +26,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ + git \ + build-essential \ + gobjc \ ++ pkg-config \ + gnustep-make \ + gnustep-base-runtime \ + libgnustep-base-dev \ +@@ -40,6 +41,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ + libcurl4-openssl-dev \ + libzip-dev \ + libytnef0-dev \ ++ libwbxml2-dev \ + curl \ + ca-certificates \ + # Runtime dependencies +@@ -68,6 +70,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ + libcurl4 \ + libzip4 \ + libytnef0 \ ++ libwbxml2-1 \ + # Download gosu + && dpkgArch="$(dpkg --print-architecture | awk -F- '{ print $NF }')" \ + && wget -O /usr/local/bin/gosu "https://github.com/tianon/gosu/releases/download/$GOSU_VERSION/gosu-$dpkgArch" \ +@@ -97,6 +100,9 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ + && ./configure --disable-debug --disable-strip \ + && make -j$(nproc) \ + && make install \ ++ && cd /tmp/sogo/ActiveSync \ ++ && . /usr/share/GNUstep/Makefiles/GNUstep.sh \ ++ && make -j$(nproc) install \ + && cd / \ + && rm -rf /tmp/sogo \ + # Strip binaries +diff --git a/docker-compose.yml b/docker-compose.yml +index 82c14749..98dccea5 100644 +--- a/docker-compose.yml ++++ b/docker-compose.yml +@@ -200,7 +200,7 @@ services: + - phpfpm + + sogo-mailcow: +- image: ghcr.io/mailcow/sogo:5.12.5-2 ++ image: ghcr.io/mailcow/sogo:5.12.5-3 + environment: + - DBNAME=${DBNAME} + - DBUSER=${DBUSER} diff --git a/tasks/mailcow__mailcow-dockerized-7111/tests/test.sh b/tasks/mailcow__mailcow-dockerized-7111/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..5ade129df686226a6099f5e4146c21e4b0f8f8c2 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7111/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace bea9ad7e8f09186bddd3e9b8cdba0d384417bd11 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/mailcow__mailcow-dockerized-7111/tests/verifier.py b/tasks/mailcow__mailcow-dockerized-7111/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7111/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/mailcow__mailcow-dockerized-7113/environment/Dockerfile b/tasks/mailcow__mailcow-dockerized-7113/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..00a9c2fdb2c1dbe011ae5f18417ac59d2e8b59d0 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7113/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/mailcow/mailcow-dockerized.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/mailcow/mailcow-dockerized.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/mailcow/mailcow-dockerized.git +WORKDIR /workspace +RUN git fetch --depth 1 origin b59869b7206287875d8b80b203330d1f9157b2be 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard b59869b7206287875d8b80b203330d1f9157b2be \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base b59869b7206287875d8b80b203330d1f9157b2be \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/mailcow__mailcow-dockerized-7113/instruction.md b/tasks/mailcow__mailcow-dockerized-7113/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9efb0c61c88f241c69ecc53bfab79ca46f7fe958 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7113/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Hotfix 2026-03 + +## Description + +Hotfix 2026-03 + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `b59869b72062`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/mailcow__mailcow-dockerized-7113/solution/patch.diff b/tasks/mailcow__mailcow-dockerized-7113/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..8bfe53b4ca5843da0b31b7c64a7ab83fa4000353 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7113/solution/patch.diff @@ -0,0 +1,51 @@ +diff --git a/data/Dockerfiles/sogo/Dockerfile b/data/Dockerfiles/sogo/Dockerfile +index 5d83c4eb..96d2e0a4 100644 +--- a/data/Dockerfiles/sogo/Dockerfile ++++ b/data/Dockerfiles/sogo/Dockerfile +@@ -26,6 +26,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ + git \ + build-essential \ + gobjc \ ++ pkg-config \ + gnustep-make \ + gnustep-base-runtime \ + libgnustep-base-dev \ +@@ -40,6 +41,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ + libcurl4-openssl-dev \ + libzip-dev \ + libytnef0-dev \ ++ libwbxml2-dev \ + curl \ + ca-certificates \ + # Runtime dependencies +@@ -68,6 +70,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ + libcurl4 \ + libzip4 \ + libytnef0 \ ++ libwbxml2-1 \ + # Download gosu + && dpkgArch="$(dpkg --print-architecture | awk -F- '{ print $NF }')" \ + && wget -O /usr/local/bin/gosu "https://github.com/tianon/gosu/releases/download/$GOSU_VERSION/gosu-$dpkgArch" \ +@@ -97,6 +100,9 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ + && ./configure --disable-debug --disable-strip \ + && make -j$(nproc) \ + && make install \ ++ && cd /tmp/sogo/ActiveSync \ ++ && . /usr/share/GNUstep/Makefiles/GNUstep.sh \ ++ && make -j$(nproc) install \ + && cd / \ + && rm -rf /tmp/sogo \ + # Strip binaries +diff --git a/docker-compose.yml b/docker-compose.yml +index 82c14749..98dccea5 100644 +--- a/docker-compose.yml ++++ b/docker-compose.yml +@@ -200,7 +200,7 @@ services: + - phpfpm + + sogo-mailcow: +- image: ghcr.io/mailcow/sogo:5.12.5-2 ++ image: ghcr.io/mailcow/sogo:5.12.5-3 + environment: + - DBNAME=${DBNAME} + - DBUSER=${DBUSER} diff --git a/tasks/mailcow__mailcow-dockerized-7113/solution/solve.sh b/tasks/mailcow__mailcow-dockerized-7113/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7113/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/mailcow__mailcow-dockerized-7113/task.toml b/tasks/mailcow__mailcow-dockerized-7113/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..58a0c071200ee63e0fd87f4faa07a1386a82939a --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7113/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/mailcow__mailcow-dockerized-7113" +description = "Hotfix 2026-03" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "mailcow-dockerized", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "mailcow/mailcow-dockerized" +ref = "b59869b7206287875d8b80b203330d1f9157b2be" +reference = "https://github.com/mailcow/mailcow-dockerized/pull/7113" +source_access = "auto" +built_at = "2026-11-16T16:09:53.230421+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:f36133519ebd76c97d7832afbf6f79909adefbf3ff5d399e1440a38c7d65fb83" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-03-10T12:50:33Z" +diff_format = "unified" +context_files = [ + "data/Dockerfiles/sogo/Dockerfile", + "docker-compose.yml", +] +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.445535+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:accbf8f9301503b870e76681b755a9a90006513236ce553be6864b478ff5d446" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/mailcow__mailcow-dockerized-7113/tests/capture.py b/tasks/mailcow__mailcow-dockerized-7113/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7113/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/mailcow__mailcow-dockerized-7113/tests/instruction.md b/tasks/mailcow__mailcow-dockerized-7113/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9efb0c61c88f241c69ecc53bfab79ca46f7fe958 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7113/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Hotfix 2026-03 + +## Description + +Hotfix 2026-03 + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `b59869b72062`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/mailcow__mailcow-dockerized-7113/tests/oracle.patch b/tasks/mailcow__mailcow-dockerized-7113/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..8bfe53b4ca5843da0b31b7c64a7ab83fa4000353 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7113/tests/oracle.patch @@ -0,0 +1,51 @@ +diff --git a/data/Dockerfiles/sogo/Dockerfile b/data/Dockerfiles/sogo/Dockerfile +index 5d83c4eb..96d2e0a4 100644 +--- a/data/Dockerfiles/sogo/Dockerfile ++++ b/data/Dockerfiles/sogo/Dockerfile +@@ -26,6 +26,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ + git \ + build-essential \ + gobjc \ ++ pkg-config \ + gnustep-make \ + gnustep-base-runtime \ + libgnustep-base-dev \ +@@ -40,6 +41,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ + libcurl4-openssl-dev \ + libzip-dev \ + libytnef0-dev \ ++ libwbxml2-dev \ + curl \ + ca-certificates \ + # Runtime dependencies +@@ -68,6 +70,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ + libcurl4 \ + libzip4 \ + libytnef0 \ ++ libwbxml2-1 \ + # Download gosu + && dpkgArch="$(dpkg --print-architecture | awk -F- '{ print $NF }')" \ + && wget -O /usr/local/bin/gosu "https://github.com/tianon/gosu/releases/download/$GOSU_VERSION/gosu-$dpkgArch" \ +@@ -97,6 +100,9 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ + && ./configure --disable-debug --disable-strip \ + && make -j$(nproc) \ + && make install \ ++ && cd /tmp/sogo/ActiveSync \ ++ && . /usr/share/GNUstep/Makefiles/GNUstep.sh \ ++ && make -j$(nproc) install \ + && cd / \ + && rm -rf /tmp/sogo \ + # Strip binaries +diff --git a/docker-compose.yml b/docker-compose.yml +index 82c14749..98dccea5 100644 +--- a/docker-compose.yml ++++ b/docker-compose.yml +@@ -200,7 +200,7 @@ services: + - phpfpm + + sogo-mailcow: +- image: ghcr.io/mailcow/sogo:5.12.5-2 ++ image: ghcr.io/mailcow/sogo:5.12.5-3 + environment: + - DBNAME=${DBNAME} + - DBUSER=${DBUSER} diff --git a/tasks/mailcow__mailcow-dockerized-7113/tests/test.sh b/tasks/mailcow__mailcow-dockerized-7113/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2c1256811332aa549b3c9c1e75a887c9f69ee4a4 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7113/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace b59869b7206287875d8b80b203330d1f9157b2be > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/mailcow__mailcow-dockerized-7113/tests/verifier.py b/tasks/mailcow__mailcow-dockerized-7113/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7113/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/mailcow__mailcow-dockerized-7121/environment/Dockerfile b/tasks/mailcow__mailcow-dockerized-7121/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a650ad4e46f61d9d040dc76441c243b8cfa33bd3 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7121/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/mailcow/mailcow-dockerized.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/mailcow/mailcow-dockerized.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/mailcow/mailcow-dockerized.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 1e0850193a4e5cee30a81c75e6acabd05c616ce5 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 1e0850193a4e5cee30a81c75e6acabd05c616ce5 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 1e0850193a4e5cee30a81c75e6acabd05c616ce5 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/mailcow__mailcow-dockerized-7121/instruction.md b/tasks/mailcow__mailcow-dockerized-7121/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8de9395d5ce4bd280842e1d626803d1249c6f7b1 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7121/instruction.md @@ -0,0 +1,45 @@ +# Issue + +**Title:** Fix theme localStorage collision with rspamd UI + +## Description + + + +## Contribution Guidelines + +* [x] I've read the [contribution guidelines](https://github.com/mailcow/mailcow-dockerized/blob/master/CONTRIBUTING.md) and wholeheartedly agree them + + + +## What does this PR include? + + +Fix theme preference collision between mailcow admin UI (/admin) and rspamd UI (/rspamd). + +Both used the same localStorage key "theme". +Because both run on the same origin, changing the theme in one UI overwrote the other. + +This PR introduces a separate key "mailcow_theme" for the mailcow UI and removes localStorage.clear(). + +### Short Description + +Fix theme collision between mailcow UI and rspamd UI. + +### Affected Containers + +- nginx-mailcow + +## Did you run tests? + +### What did you tested? + +Manual testing only. + +### What were the final results? (Awaited, got) +Awaited: mailcow ui / rspamd ui keep independent themes. +Got: Themes no longer overwrite each other. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `1e0850193a4e`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/mailcow__mailcow-dockerized-7121/solution/patch.diff b/tasks/mailcow__mailcow-dockerized-7121/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..7d9c46202fabfad5730ed12466610f547379f715 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7121/solution/patch.diff @@ -0,0 +1,51 @@ +diff --git a/data/web/js/build/013-mailcow.js b/data/web/js/build/013-mailcow.js +index d897f23e..e4893d7a 100644 +--- a/data/web/js/build/013-mailcow.js ++++ b/data/web/js/build/013-mailcow.js +@@ -345,7 +345,7 @@ $(document).ready(function() { + $('.main-logo-dark').addClass('d-none'); + if ($('#rspamd_logo').length) $('#rspamd_logo').attr('src', '/img/rspamd_logo_dark.png'); + if ($('#rspamd_logo_sm').length) $('#rspamd_logo_sm').attr('src', '/img/rspamd_logo_dark.png'); +- localStorage.setItem('theme', 'light'); ++ localStorage.setItem('mailcow_theme', 'light'); + }else{ + $('head').append(''); + $('#dark-mode-toggle').prop('checked', true); +@@ -353,7 +353,7 @@ $(document).ready(function() { + $('.main-logo-dark').removeClass('d-none'); + if ($('#rspamd_logo').length) $('#rspamd_logo').attr('src', '/img/rspamd_logo_light.png'); + if ($('#rspamd_logo_sm').length) $('#rspamd_logo_sm').attr('src', '/img/rspamd_logo_light.png'); +- localStorage.setItem('theme', 'dark'); ++ localStorage.setItem('mailcow_theme', 'dark'); + } + } + +diff --git a/data/web/js/site/index.js b/data/web/js/site/index.js +index 4c812a37..29b72f0d 100644 +--- a/data/web/js/site/index.js ++++ b/data/web/js/site/index.js +@@ -1,5 +1,6 @@ + $(document).ready(function() { +- var theme = localStorage.getItem("theme"); +- localStorage.clear(); +- localStorage.setItem("theme", theme); ++ var theme = localStorage.getItem("mailcow_theme"); ++ if (theme !== null) { ++ localStorage.setItem("mailcow_theme", theme); ++ } + }); +diff --git a/data/web/templates/base.twig b/data/web/templates/base.twig +index 4290edae..e1708950 100644 +--- a/data/web/templates/base.twig ++++ b/data/web/templates/base.twig +@@ -11,8 +11,8 @@ + +