diff --git a/tasks/mailcow__mailcow-dockerized-7177/tests/test.sh b/tasks/mailcow__mailcow-dockerized-7177/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2632ce5a64e4a2a0ef29fcab53f599b74b143243 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7177/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace ec2482528033d2a7c240ccf2bf4eef3121a47fa7 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "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-7177/tests/verifier.py b/tasks/mailcow__mailcow-dockerized-7177/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7177/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "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-7190/environment/Dockerfile b/tasks/mailcow__mailcow-dockerized-7190/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..797aa5b5c53feabea525b7c3c3764a24217ee0d6 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7190/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git 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 dc15994d4014a0b0cad2d408090aae9e7fbea3cd 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard dc15994d4014a0b0cad2d408090aae9e7fbea3cd \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base dc15994d4014a0b0cad2d408090aae9e7fbea3cd \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -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-7190/instruction.md b/tasks/mailcow__mailcow-dockerized-7190/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..96e59b7e5f757609044a53d82bbcea065b91848e --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7190/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 `dc15994d4014`. Edit files in place; the verifier captures your changes via `git diff` 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-7190/solution/patch.diff b/tasks/mailcow__mailcow-dockerized-7190/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..d111aa195f430bcab31977f0b379812f1016ced4 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7190/solution/patch.diff @@ -0,0 +1,200 @@ +diff --git a/data/web/lang/lang.az-az.json b/data/web/lang/lang.az-az.json +new file mode 100644 +index 00000000..0862f691 +--- /dev/null ++++ b/data/web/lang/lang.az-az.json +@@ -0,0 +1,5 @@ ++{ ++ "acl": { ++ "login_as": "E-poçt qutusu istifadəçisi olaraq daxil ol" ++ } ++} +diff --git a/data/web/lang/lang.pt-br.json b/data/web/lang/lang.pt-br.json +index b01d9765..24105db1 100644 +--- a/data/web/lang/lang.pt-br.json ++++ b/data/web/lang/lang.pt-br.json +@@ -111,7 +111,8 @@ + "validation_success": "Validado com sucesso", + "dry": "Simular sincronização", + "internal": "Interno", +- "internal_info": "Aliases internos são acessíveis apenas a partir do próprio domínio ou alias de domínio." ++ "internal_info": "Aliases internos são acessíveis apenas a partir do próprio domínio ou alias de domínio.", ++ "sender_allowed": "Permitir enviar como este alias" + }, + "admin": { + "access": "Acesso", +@@ -151,7 +152,7 @@ + "arrival_time": "Hora de chegada (hora do servidor)", + "authed_user": "Usuário autoritário", + "ays": "Tem certeza de que deseja continuar?", +- "ban_list_info": "Veja uma lista de IPs banidos abaixo: rede (tempo restante de banimento) - [ações].
Os IPs na fila para serem desbanidos serão removidos da lista de banimentos ativos em alguns segundos.
Rótulos vermelhos indicam proibições permanentes ativas na lista negra.", ++ "ban_list_info": "Veja abaixo a lista de IPs banidos: rede (tempo restante do banimento) - [ações].
IPs na fila para serem desbanidos serão removidos da lista de banimentos ativos em alguns segundos.
Rótulos vermelhos indicam banimentos permanentes ativos na lista de bloqueio.", + "change_logo": "Alterar logotipo", + "logo_normal_label": "Normal", + "logo_dark_label": "Invertido para o modo escuro", +@@ -188,9 +189,9 @@ + "excludes": "Exclui esses destinatários", + "f2b_ban_time": "Tempo (s) de proibição", + "f2b_ban_time_increment": "O tempo de banimento é incrementado com cada banimento", +- "f2b_blacklist": "Redes/hosts na lista negra", ++ "f2b_blacklist": "Redes/hosts na lista de bloqueio", + "f2b_filter": "Filtros Regex", +- "f2b_list_info": "Um host ou rede na lista negra sempre superará uma entidade na lista branca. As atualizações da lista levarão alguns segundos para serem aplicadas.", ++ "f2b_list_info": "Um host ou rede na lista de bloqueio sempre terá prioridade sobre uma entidade na lista de permissões. As atualizações das listas levarão alguns segundos para serem aplicadas.", + "f2b_manage_external": "Gerenciar Fail2Ban externamente", + "f2b_manage_external_info": "O Fail2ban ainda manterá a lista de banimentos, mas não definirá ativamente regras para bloquear o tráfego. Use a lista de banimento gerada abaixo para bloquear externamente o tráfego.", + "f2b_max_attempts": "Máximo de tentativas", +@@ -200,7 +201,7 @@ + "f2b_parameters": "Parâmetros do Fail2ban", + "f2b_regex_info": "Registros considerados: SoGo, Postfix, Dovecot, PHP-FPM.", + "f2b_retry_window": "Repita a (s) janela (s) para o máximo de tentativas", +- "f2b_whitelist": "Redes/hosts incluídos na lista branca", ++ "f2b_whitelist": "Redes/hosts na lista de permissões", + "filter_table": "Tabela de filtros", + "forwarding_hosts": "Anfitriões de encaminhamento", + "forwarding_hosts_add_hint": "Você pode especificar endereços IPv4/IPv6, redes em notação CIDR, nomes de host (que serão resolvidos para endereços IP) ou nomes de domínio (que serão resolvidos para endereços IP consultando registros SPF ou, na ausência deles, registros MX).", +@@ -320,8 +321,8 @@ + "rspamd_com_settings": "Um nome de configuração será gerado automaticamente, veja os exemplos de predefinições abaixo. Para obter mais detalhes, consulte a documentação do Rspamd", + "rspamd_global_filters": "Mapas de filtro globais", + "rspamd_global_filters_agree": "Eu vou ter cuidado!", +- "rspamd_global_filters_info": "Os mapas de filtros globais contêm diferentes tipos de listas negras e brancas globais.", +- "rspamd_global_filters_regex": "Seus nomes explicam seu propósito. Todo o conteúdo deve conter uma expressão regular válida no formato “/padrão/opções” (por exemplo, /. + @domain\\ .tld/i).
\r\n Embora verificações rudimentares estejam sendo executadas em cada linha de regex, a funcionalidade do Rspamd pode ser interrompida se não conseguir ler a sintaxe corretamente.
\r\n O Rspamd tentará ler o conteúdo do mapa quando alterado. Se você tiver problemas, reinicie o Rspamd para forçar o recarregamento do mapa.
Os elementos da lista negra são excluídos da quarentena.", ++ "rspamd_global_filters_info": "Os mapas de filtros globais contêm diferentes tipos de listas globais de bloqueio e de permissões.", ++ "rspamd_global_filters_regex": "Os nomes explicam sua finalidade. Todo o conteúdo deve conter uma expressão regular válida no formato \"/padrão/opções\" (por exemplo, /.[+@domain.tld](mailto:+@domain.tld)/i).
\nEmbora verificações básicas sejam executadas em cada linha de regex, a funcionalidade do Rspamd pode ser comprometida se ele não conseguir ler a sintaxe corretamente.
\nO Rspamd tentará ler o conteúdo do mapa quando ele for alterado. Se você tiver problemas, reinicie o Rspamd para forçar o recarregamento do mapa.
Elementos na lista de bloqueio são excluídos da quarentena.", + "rspamd_settings_map": "Mapa de configurações do Rspamd", + "sal_level": "Nível de humor", + "save": "Salvar alterações", +@@ -556,7 +557,9 @@ + "mode_invalid": "Modo %s é inválido", + "mx_invalid": "Registro MX %s é inválido", + "required_data_missing": "Dados obrigatórios %s estão ausentes", +- "version_invalid": "Versão %s é inválida" ++ "version_invalid": "Versão %s é inválida", ++ "tfa_removal_blocked": "A autenticação de dois fatores não pode ser removida, pois é obrigatória para a sua conta.", ++ "quarantine_category_invalid": "A categoria da quarentena deve ser uma das seguintes: add_header, reject, all" + }, + "datatables": { + "collapse_all": "Recolher tudo", +@@ -746,13 +749,13 @@ + "sieve_desc": "Breve descrição", + "sieve_type": "Tipo de filtro", + "skipcrossduplicates": "Ignore mensagens duplicadas entre pastas (primeiro a chegar, primeiro a ser servido)", +- "sogo_access": "Encaminhamento direto para o SOGoo", +- "sogo_access_info": "Depois de fazer login, o usuário é automaticamente redirecionado para o SOGo.", ++ "sogo_access": "Encaminhamento direto para o SOGo", ++ "sogo_access_info": "Após o login, o usuário é automaticamente redirecionado para o SOGo.", + "sogo_visible": "O alias é visível no SoGo", + "sogo_visible_info": "Essa opção afeta somente objetos, que podem ser exibidos no SoGo (endereços de alias compartilhados ou não compartilhados apontando para pelo menos uma mailbox local). Se estiver oculto, um alias não aparecerá como remetente selecionável no SoGo.", + "spam_alias": "Crie ou altere endereços de alias com limite de tempo", + "spam_filter": "Filtro de spam", +- "spam_policy": "Adicionar ou remover itens da lista branca/negra", ++ "spam_policy": "Adicionar ou remover itens da lista de permissões/bloqueio", + "spam_score": "Defina uma pontuação de spam personalizada", + "subfolder2": "Sincronizar na subpasta no destino
(vazio = não usar subpasta)", + "syncjob": "Editar tarefa de sincronização", +@@ -781,7 +784,9 @@ + "mta_sts_max_age_info": "Tempo em segundos que servidores de email de recepção podem armazenar esta política em cache até buscar novamente.", + "mta_sts_mx": "Servidor MX", + "mta_sts_mx_info": "Permite envio apenas para nomes de host de servidor de email explicitamente listados; o MTA de envio verifica se o nome do host DNS MX corresponde à lista de políticas e permite entrega apenas com certificado TLS válido (protege contra MITM).", +- "mta_sts_mx_notice": "Múltiplos servidores MX podem ser especificados (separados por vírgulas)." ++ "mta_sts_mx_notice": "Múltiplos servidores MX podem ser especificados (separados por vírgulas).", ++ "sender_allowed": "Permitir enviar como este alias", ++ "sender_allowed_info": "Se desativado, este alias poderá apenas receber e-mails. Use a ACL de remetente para substituir essa configuração e conceder a caixas de correio específicas permissão para enviar." + }, + "fido2": { + "confirm": "Confirme", +@@ -970,7 +975,7 @@ + "recipient_map_new": "Novo destinatário", + "recipient_map_new_info": "O destino do mapa do destinatário deve ser um endereço de e-mail válido ou um nome de domínio.", + "recipient_map_old": "Destinatário original", +- "recipient_map_old_info": "O destino original do mapa de um destinatário deve ser um endereço de e-mail válido ou um nome de domínio.", ++ "recipient_map_old_info": "O destino original do mapa de destinatário deve ser um endereço de e-mail válido ou um nome de domínio.", + "recipient_maps": "Mapas de destinatários", + "relay_all": "Retransmita todos os destinatários", + "relay_unknown": "Retransmitir mailboxes desconhecidas", +@@ -1061,7 +1066,7 @@ + "notified": "Notificado", + "qhandler_success": "Solicitação enviada com sucesso para o sistema. Agora você pode fechar a janela.", + "qid": "Respand AID", +- "qinfo": "O sistema de quarentena salvará as mensagens rejeitadas no banco de dados (o remetente não terá a impressão de uma mensagem entregue), bem como as mensagens, que são entregues como cópia na pasta Lixo eletrônico de uma mailbox.\n
“Aprenda como spam e exclua” aprenderá uma mensagem como spam por meio do Teorema de Bayes e também calculará hashes difusos para negar mensagens semelhantes no futuro.\n
Esteja ciente de que aprender várias mensagens pode ser demorado, dependendo do seu sistema.
Os elementos da lista negra são excluídos da quarentena.", ++ "qinfo": "O sistema de quarentena irá salvar no banco de dados os e-mails rejeitados (o remetente não terá a impressão de que o e-mail foi entregue), bem como os e-mails que são entregues como cópia na pasta de spam de uma mailbox.\n
“Aprender como spam e excluir” irá classificar a mensagem como spam por meio do Teorema de Bayes e também calcular hashes fuzzy para bloquear mensagens semelhantes no futuro.\n
Esteja ciente de que o aprendizado de múltiplas mensagens pode, dependendo do seu sistema, levar tempo.
Elementos na lista de bloqueio são excluídos da quarentena.", + "qitem": "Item de quarentena", + "quarantine": "Quarentena", + "quick_actions": "Ações", +@@ -1237,7 +1242,12 @@ + "webauthn": "Autenticação WebAuthn", + "waiting_usb_auth": "Aguardando o dispositivo USB...

Toque no botão no seu dispositivo USB agora.", + "waiting_usb_register": "Aguardando o dispositivo USB...

Digite sua senha acima e confirme seu registro tocando no botão no seu dispositivo USB.", +- "yubi_otp": "Autenticação Yubico OTP" ++ "yubi_otp": "Autenticação Yubico OTP", ++ "force_tfa": "Forçar o cadastro de 2FA no login", ++ "force_tfa_info": "O usuário será obrigado a configurar a autenticação de dois fatores antes de acessar o painel.", ++ "setup_title": "Autenticação de Dois Fatores Obrigatória", ++ "setup_required": "Sua conta exige autenticação de dois fatores. Configure um método de 2FA para continuar.", ++ "cancel_setup": "Cancelar e sair" + }, + "user": { + "action": "Ação", +@@ -1276,7 +1286,7 @@ + "delete_ays": "Confirme o processo de exclusão.", + "direct_aliases": "Endereços de alias diretos", + "direct_aliases_desc": "Os endereços de alias diretos são afetados pelo filtro de spam e pelas configurações da política TLS.", +- "direct_protocol_access": "Esse usuário da mailbox tem acesso externo direto aos seguintes protocolos e aplicativos. Essa configuração é controlada pelo administrador. As senhas de aplicativos podem ser criadas para conceder acesso a protocolos e aplicativos individuais.
O botão “Login no webmail” fornece login único no SoGo e está sempre disponível.", ++ "direct_protocol_access": "Este usuário da mailbox possui acesso direto e externo aos seguintes protocolos e aplicações. Esta configuração é controlada pelo seu administrador. Senhas de aplicativo podem ser criadas para conceder acesso a protocolos e aplicações específicos.
O botão “Webmail” fornece login único (SSO) para o SOGo e está sempre disponível.", + "eas_reset": "Redefinir o cache do dispositivo ActiveSync", + "eas_reset_help": "Em muitos casos, uma redefinição do cache do dispositivo ajudará a recuperar um perfil quebrado do ActiveSync.
Atenção: Todos os elementos serão baixados novamente!", + "eas_reset_now": "Reinicie agora", +@@ -1352,12 +1362,12 @@ + "sogo_profile_reset": "Redefinir perfil SoGo", + "sogo_profile_reset_help": "Isso destruirá o perfil SoGo de um usuário e excluirá todos os dados de contato e calendário irrecuperáveis.", + "sogo_profile_reset_now": "Redefina o perfil agora", +- "spam_aliases": "Aliases de e-mail temporários", ++ "spam_aliases": "Aliases de e-mail de spam", + "spam_score_reset": "Redefinir para o padrão do servidor", + "spamfilter": "Filtro de spam", + "spamfilter_behavior": "Avaliação", +- "spamfilter_bl": "Lista negra", +- "spamfilter_bl_desc": "Endereços de e-mail na lista negra para sempre serem classificados como spam e rejeitados. E-mails rejeitados não serão copiados para a quarentena. Podem ser usados curingas. Um filtro só é aplicado a aliases diretos (aliases com uma única caixa de correio de destino), excluindo aliases abrangentes e a própria mailbox.", ++ "spamfilter_bl": "Lista de bloqueio", ++ "spamfilter_bl_desc": "Endereços de e-mail na lista de bloqueio para sempre classificar como spam e rejeitados. E-mails rejeitados não serão copiados para a quarentena. Coringas podem ser utilizados. O filtro é aplicado apenas a aliases diretos (aliases com uma única mailbox de destino), excluindo aliases catch-all e a própria mailbox.", + "spamfilter_default_score": "Valores padrão", + "spamfilter_green": "Verde: esta mensagem não é spam", + "spamfilter_hint": "O primeiro valor descreve a “pontuação baixa de spam”, o segundo representa a “alta pontuação de spam”.", +@@ -1368,8 +1378,8 @@ + "spamfilter_table_empty": "Não há dados para exibir", + "spamfilter_table_remove": "remover", + "spamfilter_table_rule": "Regra", +- "spamfilter_wl": "Lista branca", +- "spamfilter_wl_desc": "Os endereços de e-mail incluídos na lista branca são programados para nunca serem classificados como spam. Podem ser usados curingas. Um filtro só é aplicado a aliases diretos (aliases com uma única mailbox de destino), excluindo aliases abrangentes e a própria mailbox.", ++ "spamfilter_wl": "Lista de permissões", ++ "spamfilter_wl_desc": "Endereços de e-mail na lista de permissões são configurados para nunca serem classificados como spam. Coringas podem ser utilizados. O filtro é aplicado apenas a aliases diretos (aliases com uma única mailbox de destino), excluindo aliases catch-all e a própria mailbox.", + "spamfilter_yellow": "Amarelo: esta mensagem pode ser spam, será marcada como spam e movida para sua pasta de lixo eletrônico", + "status": "Status", + "sync_jobs": "Trabalhos de sincronização", +@@ -1408,7 +1418,11 @@ + "authentication": "Autenticação", + "overview": "Visão geral", + "protocols": "Protocolos", +- "tfa_info": "A autenticação de dois fatores ajuda a proteger sua conta. Se você habilitá-la, precisará de senhas de aplicativo para fazer login em aplicativos ou serviços que não suportam autenticação de dois fatores (por exemplo, clientes de email)." ++ "tfa_info": "A autenticação de dois fatores ajuda a proteger sua conta. Se você habilitá-la, precisará de senhas de aplicativo para fazer login em aplicativos ou serviços que não suportam autenticação de dois fatores (por exemplo, clientes de email).", ++ "expire_never": "Nunca expirar", ++ "forever": "Para sempre", ++ "pw_update_required": "Sua conta exige a alteração de senha. Defina uma nova senha para continuar.", ++ "spam_aliases_info": "Um alias de spam é um endereço de e-mail temporário que pode ser usado para proteger endereços de e-mail reais.
Opcionalmente, pode-se definir um tempo de expiração para que o alias seja automaticamente desativado após o período definido, descartando efetivamente endereços que tenham sido abusados ou vazados." + }, + "warning": { + "cannot_delete_self": "Não é possível excluir o usuário conectado", +diff --git a/data/web/lang/lang.si-si.json b/data/web/lang/lang.si-si.json +index 5b7b8574..f5ba53f9 100644 +--- a/data/web/lang/lang.si-si.json ++++ b/data/web/lang/lang.si-si.json +@@ -558,7 +558,8 @@ + "mode_invalid": "Način %s ni veljaven", + "mx_invalid": "Zapis MX %s je neveljaven", + "version_invalid": "Različica %s je neveljavna", +- "tfa_removal_blocked": "Dvofaktorske avtentikacije ni mogoče odstraniti, ker je obvezna za vaš račun." ++ "tfa_removal_blocked": "Dvofaktorske avtentikacije ni mogoče odstraniti, ker je obvezna za vaš račun.", ++ "quarantine_category_invalid": "Kategorija karantene mora biti ena od: add_header, reject, all" + }, + "debug": { + "containers_info": "Informacije o zabojniku", diff --git a/tasks/mailcow__mailcow-dockerized-7190/solution/solve.sh b/tasks/mailcow__mailcow-dockerized-7190/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7190/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo 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-7190/task.toml b/tasks/mailcow__mailcow-dockerized-7190/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..3f1f2664afef816292c48ac21fbac7b13fcc3577 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7190/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/mailcow__mailcow-dockerized-7190" +description = "Translations update from Weblate" + +[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 = "dc15994d4014a0b0cad2d408090aae9e7fbea3cd" +reference = "https://github.com/mailcow/mailcow-dockerized/pull/7190" +source_access = "auto" +built_at = "2026-11-16T16:09:53.208878+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:4c64d089741d98afe9d18a09f8252aa68801c1249898ac7d77699b192a2cf825" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-04-11T19:25:03Z" +diff_format = "unified" +context_files = [ + "data/web/lang/lang.az-az.json", + "data/web/lang/lang.pt-br.json", + "data/web/lang/lang.si-si.json", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 66 +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.449509+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:5e3d8815edff56221b46a2ee254b36278f4207298586be74b55b48b726d03c16" +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-7190/tests/capture.py b/tasks/mailcow__mailcow-dockerized-7190/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7190/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture 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-7190/tests/instruction.md b/tasks/mailcow__mailcow-dockerized-7190/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..96e59b7e5f757609044a53d82bbcea065b91848e --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7190/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 `dc15994d4014`. Edit files in place; the verifier captures your changes via `git diff` 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-7190/tests/oracle.patch b/tasks/mailcow__mailcow-dockerized-7190/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..d111aa195f430bcab31977f0b379812f1016ced4 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7190/tests/oracle.patch @@ -0,0 +1,200 @@ +diff --git a/data/web/lang/lang.az-az.json b/data/web/lang/lang.az-az.json +new file mode 100644 +index 00000000..0862f691 +--- /dev/null ++++ b/data/web/lang/lang.az-az.json +@@ -0,0 +1,5 @@ ++{ ++ "acl": { ++ "login_as": "E-poçt qutusu istifadəçisi olaraq daxil ol" ++ } ++} +diff --git a/data/web/lang/lang.pt-br.json b/data/web/lang/lang.pt-br.json +index b01d9765..24105db1 100644 +--- a/data/web/lang/lang.pt-br.json ++++ b/data/web/lang/lang.pt-br.json +@@ -111,7 +111,8 @@ + "validation_success": "Validado com sucesso", + "dry": "Simular sincronização", + "internal": "Interno", +- "internal_info": "Aliases internos são acessíveis apenas a partir do próprio domínio ou alias de domínio." ++ "internal_info": "Aliases internos são acessíveis apenas a partir do próprio domínio ou alias de domínio.", ++ "sender_allowed": "Permitir enviar como este alias" + }, + "admin": { + "access": "Acesso", +@@ -151,7 +152,7 @@ + "arrival_time": "Hora de chegada (hora do servidor)", + "authed_user": "Usuário autoritário", + "ays": "Tem certeza de que deseja continuar?", +- "ban_list_info": "Veja uma lista de IPs banidos abaixo: rede (tempo restante de banimento) - [ações].
Os IPs na fila para serem desbanidos serão removidos da lista de banimentos ativos em alguns segundos.
Rótulos vermelhos indicam proibições permanentes ativas na lista negra.", ++ "ban_list_info": "Veja abaixo a lista de IPs banidos: rede (tempo restante do banimento) - [ações].
IPs na fila para serem desbanidos serão removidos da lista de banimentos ativos em alguns segundos.
Rótulos vermelhos indicam banimentos permanentes ativos na lista de bloqueio.", + "change_logo": "Alterar logotipo", + "logo_normal_label": "Normal", + "logo_dark_label": "Invertido para o modo escuro", +@@ -188,9 +189,9 @@ + "excludes": "Exclui esses destinatários", + "f2b_ban_time": "Tempo (s) de proibição", + "f2b_ban_time_increment": "O tempo de banimento é incrementado com cada banimento", +- "f2b_blacklist": "Redes/hosts na lista negra", ++ "f2b_blacklist": "Redes/hosts na lista de bloqueio", + "f2b_filter": "Filtros Regex", +- "f2b_list_info": "Um host ou rede na lista negra sempre superará uma entidade na lista branca. As atualizações da lista levarão alguns segundos para serem aplicadas.", ++ "f2b_list_info": "Um host ou rede na lista de bloqueio sempre terá prioridade sobre uma entidade na lista de permissões. As atualizações das listas levarão alguns segundos para serem aplicadas.", + "f2b_manage_external": "Gerenciar Fail2Ban externamente", + "f2b_manage_external_info": "O Fail2ban ainda manterá a lista de banimentos, mas não definirá ativamente regras para bloquear o tráfego. Use a lista de banimento gerada abaixo para bloquear externamente o tráfego.", + "f2b_max_attempts": "Máximo de tentativas", +@@ -200,7 +201,7 @@ + "f2b_parameters": "Parâmetros do Fail2ban", + "f2b_regex_info": "Registros considerados: SoGo, Postfix, Dovecot, PHP-FPM.", + "f2b_retry_window": "Repita a (s) janela (s) para o máximo de tentativas", +- "f2b_whitelist": "Redes/hosts incluídos na lista branca", ++ "f2b_whitelist": "Redes/hosts na lista de permissões", + "filter_table": "Tabela de filtros", + "forwarding_hosts": "Anfitriões de encaminhamento", + "forwarding_hosts_add_hint": "Você pode especificar endereços IPv4/IPv6, redes em notação CIDR, nomes de host (que serão resolvidos para endereços IP) ou nomes de domínio (que serão resolvidos para endereços IP consultando registros SPF ou, na ausência deles, registros MX).", +@@ -320,8 +321,8 @@ + "rspamd_com_settings": "Um nome de configuração será gerado automaticamente, veja os exemplos de predefinições abaixo. Para obter mais detalhes, consulte a documentação do Rspamd", + "rspamd_global_filters": "Mapas de filtro globais", + "rspamd_global_filters_agree": "Eu vou ter cuidado!", +- "rspamd_global_filters_info": "Os mapas de filtros globais contêm diferentes tipos de listas negras e brancas globais.", +- "rspamd_global_filters_regex": "Seus nomes explicam seu propósito. Todo o conteúdo deve conter uma expressão regular válida no formato “/padrão/opções” (por exemplo, /. + @domain\\ .tld/i).
\r\n Embora verificações rudimentares estejam sendo executadas em cada linha de regex, a funcionalidade do Rspamd pode ser interrompida se não conseguir ler a sintaxe corretamente.
\r\n O Rspamd tentará ler o conteúdo do mapa quando alterado. Se você tiver problemas, reinicie o Rspamd para forçar o recarregamento do mapa.
Os elementos da lista negra são excluídos da quarentena.", ++ "rspamd_global_filters_info": "Os mapas de filtros globais contêm diferentes tipos de listas globais de bloqueio e de permissões.", ++ "rspamd_global_filters_regex": "Os nomes explicam sua finalidade. Todo o conteúdo deve conter uma expressão regular válida no formato \"/padrão/opções\" (por exemplo, /.[+@domain.tld](mailto:+@domain.tld)/i).
\nEmbora verificações básicas sejam executadas em cada linha de regex, a funcionalidade do Rspamd pode ser comprometida se ele não conseguir ler a sintaxe corretamente.
\nO Rspamd tentará ler o conteúdo do mapa quando ele for alterado. Se você tiver problemas, reinicie o Rspamd para forçar o recarregamento do mapa.
Elementos na lista de bloqueio são excluídos da quarentena.", + "rspamd_settings_map": "Mapa de configurações do Rspamd", + "sal_level": "Nível de humor", + "save": "Salvar alterações", +@@ -556,7 +557,9 @@ + "mode_invalid": "Modo %s é inválido", + "mx_invalid": "Registro MX %s é inválido", + "required_data_missing": "Dados obrigatórios %s estão ausentes", +- "version_invalid": "Versão %s é inválida" ++ "version_invalid": "Versão %s é inválida", ++ "tfa_removal_blocked": "A autenticação de dois fatores não pode ser removida, pois é obrigatória para a sua conta.", ++ "quarantine_category_invalid": "A categoria da quarentena deve ser uma das seguintes: add_header, reject, all" + }, + "datatables": { + "collapse_all": "Recolher tudo", +@@ -746,13 +749,13 @@ + "sieve_desc": "Breve descrição", + "sieve_type": "Tipo de filtro", + "skipcrossduplicates": "Ignore mensagens duplicadas entre pastas (primeiro a chegar, primeiro a ser servido)", +- "sogo_access": "Encaminhamento direto para o SOGoo", +- "sogo_access_info": "Depois de fazer login, o usuário é automaticamente redirecionado para o SOGo.", ++ "sogo_access": "Encaminhamento direto para o SOGo", ++ "sogo_access_info": "Após o login, o usuário é automaticamente redirecionado para o SOGo.", + "sogo_visible": "O alias é visível no SoGo", + "sogo_visible_info": "Essa opção afeta somente objetos, que podem ser exibidos no SoGo (endereços de alias compartilhados ou não compartilhados apontando para pelo menos uma mailbox local). Se estiver oculto, um alias não aparecerá como remetente selecionável no SoGo.", + "spam_alias": "Crie ou altere endereços de alias com limite de tempo", + "spam_filter": "Filtro de spam", +- "spam_policy": "Adicionar ou remover itens da lista branca/negra", ++ "spam_policy": "Adicionar ou remover itens da lista de permissões/bloqueio", + "spam_score": "Defina uma pontuação de spam personalizada", + "subfolder2": "Sincronizar na subpasta no destino
(vazio = não usar subpasta)", + "syncjob": "Editar tarefa de sincronização", +@@ -781,7 +784,9 @@ + "mta_sts_max_age_info": "Tempo em segundos que servidores de email de recepção podem armazenar esta política em cache até buscar novamente.", + "mta_sts_mx": "Servidor MX", + "mta_sts_mx_info": "Permite envio apenas para nomes de host de servidor de email explicitamente listados; o MTA de envio verifica se o nome do host DNS MX corresponde à lista de políticas e permite entrega apenas com certificado TLS válido (protege contra MITM).", +- "mta_sts_mx_notice": "Múltiplos servidores MX podem ser especificados (separados por vírgulas)." ++ "mta_sts_mx_notice": "Múltiplos servidores MX podem ser especificados (separados por vírgulas).", ++ "sender_allowed": "Permitir enviar como este alias", ++ "sender_allowed_info": "Se desativado, este alias poderá apenas receber e-mails. Use a ACL de remetente para substituir essa configuração e conceder a caixas de correio específicas permissão para enviar." + }, + "fido2": { + "confirm": "Confirme", +@@ -970,7 +975,7 @@ + "recipient_map_new": "Novo destinatário", + "recipient_map_new_info": "O destino do mapa do destinatário deve ser um endereço de e-mail válido ou um nome de domínio.", + "recipient_map_old": "Destinatário original", +- "recipient_map_old_info": "O destino original do mapa de um destinatário deve ser um endereço de e-mail válido ou um nome de domínio.", ++ "recipient_map_old_info": "O destino original do mapa de destinatário deve ser um endereço de e-mail válido ou um nome de domínio.", + "recipient_maps": "Mapas de destinatários", + "relay_all": "Retransmita todos os destinatários", + "relay_unknown": "Retransmitir mailboxes desconhecidas", +@@ -1061,7 +1066,7 @@ + "notified": "Notificado", + "qhandler_success": "Solicitação enviada com sucesso para o sistema. Agora você pode fechar a janela.", + "qid": "Respand AID", +- "qinfo": "O sistema de quarentena salvará as mensagens rejeitadas no banco de dados (o remetente não terá a impressão de uma mensagem entregue), bem como as mensagens, que são entregues como cópia na pasta Lixo eletrônico de uma mailbox.\n
“Aprenda como spam e exclua” aprenderá uma mensagem como spam por meio do Teorema de Bayes e também calculará hashes difusos para negar mensagens semelhantes no futuro.\n
Esteja ciente de que aprender várias mensagens pode ser demorado, dependendo do seu sistema.
Os elementos da lista negra são excluídos da quarentena.", ++ "qinfo": "O sistema de quarentena irá salvar no banco de dados os e-mails rejeitados (o remetente não terá a impressão de que o e-mail foi entregue), bem como os e-mails que são entregues como cópia na pasta de spam de uma mailbox.\n
“Aprender como spam e excluir” irá classificar a mensagem como spam por meio do Teorema de Bayes e também calcular hashes fuzzy para bloquear mensagens semelhantes no futuro.\n
Esteja ciente de que o aprendizado de múltiplas mensagens pode, dependendo do seu sistema, levar tempo.
Elementos na lista de bloqueio são excluídos da quarentena.", + "qitem": "Item de quarentena", + "quarantine": "Quarentena", + "quick_actions": "Ações", +@@ -1237,7 +1242,12 @@ + "webauthn": "Autenticação WebAuthn", + "waiting_usb_auth": "Aguardando o dispositivo USB...

Toque no botão no seu dispositivo USB agora.", + "waiting_usb_register": "Aguardando o dispositivo USB...

Digite sua senha acima e confirme seu registro tocando no botão no seu dispositivo USB.", +- "yubi_otp": "Autenticação Yubico OTP" ++ "yubi_otp": "Autenticação Yubico OTP", ++ "force_tfa": "Forçar o cadastro de 2FA no login", ++ "force_tfa_info": "O usuário será obrigado a configurar a autenticação de dois fatores antes de acessar o painel.", ++ "setup_title": "Autenticação de Dois Fatores Obrigatória", ++ "setup_required": "Sua conta exige autenticação de dois fatores. Configure um método de 2FA para continuar.", ++ "cancel_setup": "Cancelar e sair" + }, + "user": { + "action": "Ação", +@@ -1276,7 +1286,7 @@ + "delete_ays": "Confirme o processo de exclusão.", + "direct_aliases": "Endereços de alias diretos", + "direct_aliases_desc": "Os endereços de alias diretos são afetados pelo filtro de spam e pelas configurações da política TLS.", +- "direct_protocol_access": "Esse usuário da mailbox tem acesso externo direto aos seguintes protocolos e aplicativos. Essa configuração é controlada pelo administrador. As senhas de aplicativos podem ser criadas para conceder acesso a protocolos e aplicativos individuais.
O botão “Login no webmail” fornece login único no SoGo e está sempre disponível.", ++ "direct_protocol_access": "Este usuário da mailbox possui acesso direto e externo aos seguintes protocolos e aplicações. Esta configuração é controlada pelo seu administrador. Senhas de aplicativo podem ser criadas para conceder acesso a protocolos e aplicações específicos.
O botão “Webmail” fornece login único (SSO) para o SOGo e está sempre disponível.", + "eas_reset": "Redefinir o cache do dispositivo ActiveSync", + "eas_reset_help": "Em muitos casos, uma redefinição do cache do dispositivo ajudará a recuperar um perfil quebrado do ActiveSync.
Atenção: Todos os elementos serão baixados novamente!", + "eas_reset_now": "Reinicie agora", +@@ -1352,12 +1362,12 @@ + "sogo_profile_reset": "Redefinir perfil SoGo", + "sogo_profile_reset_help": "Isso destruirá o perfil SoGo de um usuário e excluirá todos os dados de contato e calendário irrecuperáveis.", + "sogo_profile_reset_now": "Redefina o perfil agora", +- "spam_aliases": "Aliases de e-mail temporários", ++ "spam_aliases": "Aliases de e-mail de spam", + "spam_score_reset": "Redefinir para o padrão do servidor", + "spamfilter": "Filtro de spam", + "spamfilter_behavior": "Avaliação", +- "spamfilter_bl": "Lista negra", +- "spamfilter_bl_desc": "Endereços de e-mail na lista negra para sempre serem classificados como spam e rejeitados. E-mails rejeitados não serão copiados para a quarentena. Podem ser usados curingas. Um filtro só é aplicado a aliases diretos (aliases com uma única caixa de correio de destino), excluindo aliases abrangentes e a própria mailbox.", ++ "spamfilter_bl": "Lista de bloqueio", ++ "spamfilter_bl_desc": "Endereços de e-mail na lista de bloqueio para sempre classificar como spam e rejeitados. E-mails rejeitados não serão copiados para a quarentena. Coringas podem ser utilizados. O filtro é aplicado apenas a aliases diretos (aliases com uma única mailbox de destino), excluindo aliases catch-all e a própria mailbox.", + "spamfilter_default_score": "Valores padrão", + "spamfilter_green": "Verde: esta mensagem não é spam", + "spamfilter_hint": "O primeiro valor descreve a “pontuação baixa de spam”, o segundo representa a “alta pontuação de spam”.", +@@ -1368,8 +1378,8 @@ + "spamfilter_table_empty": "Não há dados para exibir", + "spamfilter_table_remove": "remover", + "spamfilter_table_rule": "Regra", +- "spamfilter_wl": "Lista branca", +- "spamfilter_wl_desc": "Os endereços de e-mail incluídos na lista branca são programados para nunca serem classificados como spam. Podem ser usados curingas. Um filtro só é aplicado a aliases diretos (aliases com uma única mailbox de destino), excluindo aliases abrangentes e a própria mailbox.", ++ "spamfilter_wl": "Lista de permissões", ++ "spamfilter_wl_desc": "Endereços de e-mail na lista de permissões são configurados para nunca serem classificados como spam. Coringas podem ser utilizados. O filtro é aplicado apenas a aliases diretos (aliases com uma única mailbox de destino), excluindo aliases catch-all e a própria mailbox.", + "spamfilter_yellow": "Amarelo: esta mensagem pode ser spam, será marcada como spam e movida para sua pasta de lixo eletrônico", + "status": "Status", + "sync_jobs": "Trabalhos de sincronização", +@@ -1408,7 +1418,11 @@ + "authentication": "Autenticação", + "overview": "Visão geral", + "protocols": "Protocolos", +- "tfa_info": "A autenticação de dois fatores ajuda a proteger sua conta. Se você habilitá-la, precisará de senhas de aplicativo para fazer login em aplicativos ou serviços que não suportam autenticação de dois fatores (por exemplo, clientes de email)." ++ "tfa_info": "A autenticação de dois fatores ajuda a proteger sua conta. Se você habilitá-la, precisará de senhas de aplicativo para fazer login em aplicativos ou serviços que não suportam autenticação de dois fatores (por exemplo, clientes de email).", ++ "expire_never": "Nunca expirar", ++ "forever": "Para sempre", ++ "pw_update_required": "Sua conta exige a alteração de senha. Defina uma nova senha para continuar.", ++ "spam_aliases_info": "Um alias de spam é um endereço de e-mail temporário que pode ser usado para proteger endereços de e-mail reais.
Opcionalmente, pode-se definir um tempo de expiração para que o alias seja automaticamente desativado após o período definido, descartando efetivamente endereços que tenham sido abusados ou vazados." + }, + "warning": { + "cannot_delete_self": "Não é possível excluir o usuário conectado", +diff --git a/data/web/lang/lang.si-si.json b/data/web/lang/lang.si-si.json +index 5b7b8574..f5ba53f9 100644 +--- a/data/web/lang/lang.si-si.json ++++ b/data/web/lang/lang.si-si.json +@@ -558,7 +558,8 @@ + "mode_invalid": "Način %s ni veljaven", + "mx_invalid": "Zapis MX %s je neveljaven", + "version_invalid": "Različica %s je neveljavna", +- "tfa_removal_blocked": "Dvofaktorske avtentikacije ni mogoče odstraniti, ker je obvezna za vaš račun." ++ "tfa_removal_blocked": "Dvofaktorske avtentikacije ni mogoče odstraniti, ker je obvezna za vaš račun.", ++ "quarantine_category_invalid": "Kategorija karantene mora biti ena od: add_header, reject, all" + }, + "debug": { + "containers_info": "Informacije o zabojniku", diff --git a/tasks/mailcow__mailcow-dockerized-7190/tests/test.sh b/tasks/mailcow__mailcow-dockerized-7190/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..6eba34cee5ab1583525d1638ef2391edc31e5f29 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7190/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace dc15994d4014a0b0cad2d408090aae9e7fbea3cd > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "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-7190/tests/verifier.py b/tasks/mailcow__mailcow-dockerized-7190/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7190/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "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-7209/environment/Dockerfile b/tasks/mailcow__mailcow-dockerized-7209/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d6be78b9a27ea190433d2701947825c5dec09d94 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7209/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git 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 886dbcc4196e0660912d843a98ab089fe75a8e7a 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 886dbcc4196e0660912d843a98ab089fe75a8e7a \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 886dbcc4196e0660912d843a98ab089fe75a8e7a \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -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-7209/instruction.md b/tasks/mailcow__mailcow-dockerized-7209/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e67f23679cfac901bcdde7e4b1dcd40cba448550 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7209/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 `886dbcc4196e`. Edit files in place; the verifier captures your changes via `git diff` 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-7209/solution/patch.diff b/tasks/mailcow__mailcow-dockerized-7209/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..0e46274043011c54d71e1845febac1fdb3ed1f03 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7209/solution/patch.diff @@ -0,0 +1,67 @@ +diff --git a/data/conf/postfix/postscreen_access.cidr b/data/conf/postfix/postscreen_access.cidr +index 2f7891cd..285ea7a8 100644 +--- a/data/conf/postfix/postscreen_access.cidr ++++ b/data/conf/postfix/postscreen_access.cidr +@@ -1,7 +1,8 @@ +-# Whitelist generated by Postwhite v3.4 on Wed Apr 1 00:33:31 UTC 2026 ++# Whitelist generated by Postwhite v3.4 on Fri May 1 00:43:37 UTC 2026 + # https://github.com/stevejenkins/postwhite/ +-# 2246 total rules ++# 2249 total rules + 2a00:1450:4000::/36 permit ++2a00:1450:4864::/56 permit + 2a01:111:f400::/48 permit + 2a01:111:f403:2800::/53 permit + 2a01:111:f403:8000::/51 permit +@@ -31,6 +32,7 @@ + 2a02:a60:0:5::/64 permit + 2a0f:f640::/56 permit + 2c0f:fb50:4000::/36 permit ++2c0f:fb50:4864::/56 permit + 2.207.151.32/27 permit + 2.207.151.53 permit + 2.207.217.30 permit +@@ -60,8 +62,8 @@ + 8.40.222.0/23 permit + 8.40.222.250/31 permit + 12.130.86.238 permit +-13.107.213.38 permit +-13.107.246.38 permit ++13.107.213.40 permit ++13.107.246.40 permit + 13.108.16.0/20 permit + 13.110.208.0/21 permit + 13.110.209.0/24 permit +@@ -279,6 +281,7 @@ + 50.56.130.221 permit + 50.56.130.222 permit + 50.112.246.219 permit ++51.83.17.38 permit + 52.1.14.157 permit + 52.5.230.59 permit + 52.6.74.205 permit +@@ -1678,6 +1681,7 @@ + 169.148.144.0/25 permit + 169.148.144.10 permit + 169.148.146.0/23 permit ++169.148.174.10 permit + 169.148.175.3 permit + 169.148.179.3 permit + 169.148.188.0/24 permit +@@ -2227,6 +2231,7 @@ + 2001:748:400:3301::4 permit + 2404:6800:4000::/36 permit + 2404:6800:4864::/56 permit ++2603:1061:14:72::1 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 +@@ -2243,8 +2248,6 @@ + 2620:10d:c09c:400::8:1 permit + 2620:119:50c0:207::/64 permit + 2620:119:50c0:207::215 permit +-2620:1ec:46::38 permit +-2620:1ec:bdf::38 permit + 2800:3f0:4000::/36 permit + 2800:3f0:4864::/56 permit + 49.12.4.251 permit # checks.mailcow.email diff --git a/tasks/mailcow__mailcow-dockerized-7209/solution/solve.sh b/tasks/mailcow__mailcow-dockerized-7209/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7209/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo 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-7209/task.toml b/tasks/mailcow__mailcow-dockerized-7209/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..1fbfa2e020de7f74d73ea6b35914869e76af6871 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7209/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/mailcow__mailcow-dockerized-7209" +description = "[Postfix] update postscreen_access.cidr" + +[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 = "886dbcc4196e0660912d843a98ab089fe75a8e7a" +reference = "https://github.com/mailcow/mailcow-dockerized/pull/7209" +source_access = "auto" +built_at = "2026-11-16T16:09:53.207352+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:5ed386a175ce30b6646573a8a2242af08173d3c9aade9534633ae717e83991ab" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-05-02T17:15:14Z" +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 = 15 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.450019+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:52ba45342f4b122d59ea84b7c9ebc3c05c501742b6a6a3775946b9242caf0d6a" +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-7209/tests/capture.py b/tasks/mailcow__mailcow-dockerized-7209/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7209/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture 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-7209/tests/instruction.md b/tasks/mailcow__mailcow-dockerized-7209/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e67f23679cfac901bcdde7e4b1dcd40cba448550 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7209/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 `886dbcc4196e`. Edit files in place; the verifier captures your changes via `git diff` 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-7209/tests/oracle.patch b/tasks/mailcow__mailcow-dockerized-7209/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..0e46274043011c54d71e1845febac1fdb3ed1f03 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7209/tests/oracle.patch @@ -0,0 +1,67 @@ +diff --git a/data/conf/postfix/postscreen_access.cidr b/data/conf/postfix/postscreen_access.cidr +index 2f7891cd..285ea7a8 100644 +--- a/data/conf/postfix/postscreen_access.cidr ++++ b/data/conf/postfix/postscreen_access.cidr +@@ -1,7 +1,8 @@ +-# Whitelist generated by Postwhite v3.4 on Wed Apr 1 00:33:31 UTC 2026 ++# Whitelist generated by Postwhite v3.4 on Fri May 1 00:43:37 UTC 2026 + # https://github.com/stevejenkins/postwhite/ +-# 2246 total rules ++# 2249 total rules + 2a00:1450:4000::/36 permit ++2a00:1450:4864::/56 permit + 2a01:111:f400::/48 permit + 2a01:111:f403:2800::/53 permit + 2a01:111:f403:8000::/51 permit +@@ -31,6 +32,7 @@ + 2a02:a60:0:5::/64 permit + 2a0f:f640::/56 permit + 2c0f:fb50:4000::/36 permit ++2c0f:fb50:4864::/56 permit + 2.207.151.32/27 permit + 2.207.151.53 permit + 2.207.217.30 permit +@@ -60,8 +62,8 @@ + 8.40.222.0/23 permit + 8.40.222.250/31 permit + 12.130.86.238 permit +-13.107.213.38 permit +-13.107.246.38 permit ++13.107.213.40 permit ++13.107.246.40 permit + 13.108.16.0/20 permit + 13.110.208.0/21 permit + 13.110.209.0/24 permit +@@ -279,6 +281,7 @@ + 50.56.130.221 permit + 50.56.130.222 permit + 50.112.246.219 permit ++51.83.17.38 permit + 52.1.14.157 permit + 52.5.230.59 permit + 52.6.74.205 permit +@@ -1678,6 +1681,7 @@ + 169.148.144.0/25 permit + 169.148.144.10 permit + 169.148.146.0/23 permit ++169.148.174.10 permit + 169.148.175.3 permit + 169.148.179.3 permit + 169.148.188.0/24 permit +@@ -2227,6 +2231,7 @@ + 2001:748:400:3301::4 permit + 2404:6800:4000::/36 permit + 2404:6800:4864::/56 permit ++2603:1061:14:72::1 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 +@@ -2243,8 +2248,6 @@ + 2620:10d:c09c:400::8:1 permit + 2620:119:50c0:207::/64 permit + 2620:119:50c0:207::215 permit +-2620:1ec:46::38 permit +-2620:1ec:bdf::38 permit + 2800:3f0:4000::/36 permit + 2800:3f0:4864::/56 permit + 49.12.4.251 permit # checks.mailcow.email diff --git a/tasks/mailcow__mailcow-dockerized-7209/tests/test.sh b/tasks/mailcow__mailcow-dockerized-7209/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..1caaf687935bb084467b617055ee859005937797 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7209/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 886dbcc4196e0660912d843a98ab089fe75a8e7a > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "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-7209/tests/verifier.py b/tasks/mailcow__mailcow-dockerized-7209/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7209/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "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-7218/environment/Dockerfile b/tasks/mailcow__mailcow-dockerized-7218/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..9e90162b421992c4120a3b013138ae24ea23f41e --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7218/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git 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 d42c3823c434ef9a04a04b81783b945948f80b99 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard d42c3823c434ef9a04a04b81783b945948f80b99 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base d42c3823c434ef9a04a04b81783b945948f80b99 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -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-7218/instruction.md b/tasks/mailcow__mailcow-dockerized-7218/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..66d2eb77262b335750801255be55af8ca65f6124 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7218/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 `d42c3823c434`. Edit files in place; the verifier captures your changes via `git diff` 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-7218/solution/patch.diff b/tasks/mailcow__mailcow-dockerized-7218/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..a3ebf03dddb02aab4ae6cb47798ea1110ba017bb --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7218/solution/patch.diff @@ -0,0 +1,50 @@ +diff --git a/data/web/lang/lang.az-az.json b/data/web/lang/lang.az-az.json +index 0862f691..958ed8e2 100644 +--- a/data/web/lang/lang.az-az.json ++++ b/data/web/lang/lang.az-az.json +@@ -1,5 +1,17 @@ + { + "acl": { +- "login_as": "E-poçt qutusu istifadəçisi olaraq daxil ol" ++ "login_as": "E-poçt qutusu istifadəçisi olaraq daxil ol", ++ "alias_domains": "Alternativ domenlər əlavə et", ++ "app_passwds": "Tətbiq parollarını idarə et", ++ "bcc_maps": "BCC yönləndirmə xəritələri", ++ "delimiter_action": "Ayırıcı əməliyyatı", ++ "domain_desc": "Domen təsvirini dəyiş", ++ "domain_relayhost": "Domen üçün relay serveri dəyiş", ++ "eas_reset": "EAS cihazlarını sıfırla", ++ "extend_sender_acl": "Göndərən ACL-ni xarici ünvanlarla genişləndirməyə icazə ver", ++ "filters": "Filtrlər", ++ "mailbox_relayhost": "E-poçt qutusu üçün relay serveri dəyiş", ++ "prohibited": "ACL tərəfindən məhdudlaşdırılıb", ++ "protocol_access": "Protokol girişini dəyiş" + } + } +diff --git a/data/web/lang/lang.nl-nl.json b/data/web/lang/lang.nl-nl.json +index 7b341cec..6ed9e322 100644 +--- a/data/web/lang/lang.nl-nl.json ++++ b/data/web/lang/lang.nl-nl.json +@@ -27,7 +27,8 @@ + "tls_policy": "Versleutelingsbeleid", + "unlimited_quota": "Onbeperkte quota voor mailboxen", + "domain_desc": "Wijzig domeinbeschrijving", +- "pw_reset": "Toegang om mailcow gebruikers wachtwoord te resetten" ++ "pw_reset": "Toegang om mailcow gebruikers wachtwoord te resetten", ++ "domain_relayhost": "Verander relayhost voor een domein" + }, + "add": { + "activate_filter_warn": "Alle andere filters worden gedeactiveerd zolang deze geactiveerd is.", +diff --git a/data/web/lang/lang.pl-pl.json b/data/web/lang/lang.pl-pl.json +index 758d0cb4..b1ec3591 100644 +--- a/data/web/lang/lang.pl-pl.json ++++ b/data/web/lang/lang.pl-pl.json +@@ -1226,7 +1226,7 @@ + "decimal": ".", + "emptyTable": "Brak danych w tabeli", + "expand_all": "Rozszerz wszystko", +- "info": "Wyświetlanie od START do END z TOTAL wpisów", ++ "info": "Wyświetlanie od _START_ do _END_ z _TOTAL_ wpisów", + "infoEmpty": "Wyświetlanie od 0 do 0 z 0 wpisów", + "infoFiltered": "(filtrowane z _MAX_ suma wpisów)", + "thousands": ",", diff --git a/tasks/mailcow__mailcow-dockerized-7218/solution/solve.sh b/tasks/mailcow__mailcow-dockerized-7218/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7218/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo 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-7218/task.toml b/tasks/mailcow__mailcow-dockerized-7218/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ab748678166edc6db48ef7ef54c1ea7944adeae2 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7218/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/mailcow__mailcow-dockerized-7218" +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 = "d42c3823c434ef9a04a04b81783b945948f80b99" +reference = "https://github.com/mailcow/mailcow-dockerized/pull/7218" +source_access = "auto" +built_at = "2026-11-16T16:09:53.205939+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:124f2ccff4a0712f0c9eb68bfa3a03199ddf7365c96ded9277a5fc808d383c03" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-05-08T14:46:10Z" +diff_format = "unified" +context_files = [ + "data/web/lang/lang.az-az.json", + "data/web/lang/lang.nl-nl.json", + "data/web/lang/lang.pl-pl.json", +] +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.450522+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:4058821f7af55f03913917eaa2c41a51eb853a3541af9a0b6194688a7495c292" +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-7218/tests/capture.py b/tasks/mailcow__mailcow-dockerized-7218/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7218/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture 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-7218/tests/instruction.md b/tasks/mailcow__mailcow-dockerized-7218/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..66d2eb77262b335750801255be55af8ca65f6124 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7218/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 `d42c3823c434`. Edit files in place; the verifier captures your changes via `git diff` 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-7218/tests/oracle.patch b/tasks/mailcow__mailcow-dockerized-7218/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..a3ebf03dddb02aab4ae6cb47798ea1110ba017bb --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7218/tests/oracle.patch @@ -0,0 +1,50 @@ +diff --git a/data/web/lang/lang.az-az.json b/data/web/lang/lang.az-az.json +index 0862f691..958ed8e2 100644 +--- a/data/web/lang/lang.az-az.json ++++ b/data/web/lang/lang.az-az.json +@@ -1,5 +1,17 @@ + { + "acl": { +- "login_as": "E-poçt qutusu istifadəçisi olaraq daxil ol" ++ "login_as": "E-poçt qutusu istifadəçisi olaraq daxil ol", ++ "alias_domains": "Alternativ domenlər əlavə et", ++ "app_passwds": "Tətbiq parollarını idarə et", ++ "bcc_maps": "BCC yönləndirmə xəritələri", ++ "delimiter_action": "Ayırıcı əməliyyatı", ++ "domain_desc": "Domen təsvirini dəyiş", ++ "domain_relayhost": "Domen üçün relay serveri dəyiş", ++ "eas_reset": "EAS cihazlarını sıfırla", ++ "extend_sender_acl": "Göndərən ACL-ni xarici ünvanlarla genişləndirməyə icazə ver", ++ "filters": "Filtrlər", ++ "mailbox_relayhost": "E-poçt qutusu üçün relay serveri dəyiş", ++ "prohibited": "ACL tərəfindən məhdudlaşdırılıb", ++ "protocol_access": "Protokol girişini dəyiş" + } + } +diff --git a/data/web/lang/lang.nl-nl.json b/data/web/lang/lang.nl-nl.json +index 7b341cec..6ed9e322 100644 +--- a/data/web/lang/lang.nl-nl.json ++++ b/data/web/lang/lang.nl-nl.json +@@ -27,7 +27,8 @@ + "tls_policy": "Versleutelingsbeleid", + "unlimited_quota": "Onbeperkte quota voor mailboxen", + "domain_desc": "Wijzig domeinbeschrijving", +- "pw_reset": "Toegang om mailcow gebruikers wachtwoord te resetten" ++ "pw_reset": "Toegang om mailcow gebruikers wachtwoord te resetten", ++ "domain_relayhost": "Verander relayhost voor een domein" + }, + "add": { + "activate_filter_warn": "Alle andere filters worden gedeactiveerd zolang deze geactiveerd is.", +diff --git a/data/web/lang/lang.pl-pl.json b/data/web/lang/lang.pl-pl.json +index 758d0cb4..b1ec3591 100644 +--- a/data/web/lang/lang.pl-pl.json ++++ b/data/web/lang/lang.pl-pl.json +@@ -1226,7 +1226,7 @@ + "decimal": ".", + "emptyTable": "Brak danych w tabeli", + "expand_all": "Rozszerz wszystko", +- "info": "Wyświetlanie od START do END z TOTAL wpisów", ++ "info": "Wyświetlanie od _START_ do _END_ z _TOTAL_ wpisów", + "infoEmpty": "Wyświetlanie od 0 do 0 z 0 wpisów", + "infoFiltered": "(filtrowane z _MAX_ suma wpisów)", + "thousands": ",", diff --git a/tasks/mailcow__mailcow-dockerized-7218/tests/test.sh b/tasks/mailcow__mailcow-dockerized-7218/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..a5b7aaf6e9c29541714cdd6783161782512e5b3b --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7218/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace d42c3823c434ef9a04a04b81783b945948f80b99 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "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-7218/tests/verifier.py b/tasks/mailcow__mailcow-dockerized-7218/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7218/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "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-7220/environment/Dockerfile b/tasks/mailcow__mailcow-dockerized-7220/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6dbd7579cb96fe39216cffd3a501b2075708e3fc --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7220/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git 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 539c32d99c665e64afb4a3baf7f6372b2494cd4f 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 539c32d99c665e64afb4a3baf7f6372b2494cd4f \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 539c32d99c665e64afb4a3baf7f6372b2494cd4f \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -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-7220/instruction.md b/tasks/mailcow__mailcow-dockerized-7220/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3c0bb31feff077324cabcec3d6abd23bb62de7eb --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7220/instruction.md @@ -0,0 +1,26 @@ +# Issue + +**Title:** [Web] escape HTML in sieve filter edit view and queue manager + +## 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 + +Two small UI fixes that align user-controlled values with the auto-escaping pattern already used elsewhere: + +- `edit/filter.twig`: drop `|raw` on `script_data`. +- `js/site/queue.js`: route `queue_id`, `queue_name`, `sender` through the DataTables text renderer; HTML-escape `queue_id` in the inline checkbox and action link. + +### Affected Containers + +- php-fpm-mailcow + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `539c32d99c66`. Edit files in place; the verifier captures your changes via `git diff` 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-7220/solution/patch.diff b/tasks/mailcow__mailcow-dockerized-7220/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..b44b3afe55b2392450e27ecfc2ac4cf477960e94 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7220/solution/patch.diff @@ -0,0 +1,60 @@ +diff --git a/data/web/js/site/queue.js b/data/web/js/site/queue.js +index 26c15091..9adc79b5 100644 +--- a/data/web/js/site/queue.js ++++ b/data/web/js/site/queue.js +@@ -48,13 +48,13 @@ jQuery(function($){ + url: "/api/v1/get/mailq/all", + dataSrc: function(data){ + $.each(data, function (i, item) { +- item.chkbox = ''; ++ item.chkbox = ''; + rcpts = $.map(item.recipients, function(i) { + return escapeHtml(i); + }); + item.recipients = rcpts.join('
'); + item.action = ''; + }); + return data; +@@ -79,12 +79,14 @@ jQuery(function($){ + { + title: 'QID', + data: 'queue_id', +- defaultContent: '' ++ defaultContent: '', ++ render: $.fn.dataTable.render.text() + }, + { + title: 'Queue', + data: 'queue_name', +- defaultContent: '' ++ defaultContent: '', ++ render: $.fn.dataTable.render.text() + }, + { + title: lang_admin.arrival_time, +@@ -106,7 +108,8 @@ jQuery(function($){ + { + title: lang_admin.sender, + data: 'sender', +- defaultContent: '' ++ defaultContent: '', ++ render: $.fn.dataTable.render.text() + }, + { + title: lang_admin.recipients, +diff --git a/data/web/templates/edit/filter.twig b/data/web/templates/edit/filter.twig +index 124ecaf7..743f088b 100644 +--- a/data/web/templates/edit/filter.twig ++++ b/data/web/templates/edit/filter.twig +@@ -23,7 +23,7 @@ +
+ +
+- ++ +
+
+
diff --git a/tasks/mailcow__mailcow-dockerized-7220/solution/solve.sh b/tasks/mailcow__mailcow-dockerized-7220/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7220/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo 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-7220/task.toml b/tasks/mailcow__mailcow-dockerized-7220/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..240ea1d27f2ecef7a817da8cdb7c13a6298c5e11 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7220/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/mailcow__mailcow-dockerized-7220" +description = "[Web] escape HTML in sieve filter edit view and queue manager" + +[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 = "539c32d99c665e64afb4a3baf7f6372b2494cd4f" +reference = "https://github.com/mailcow/mailcow-dockerized/pull/7220" +source_access = "auto" +built_at = "2026-11-16T16:09:53.193795+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:1d18e2be6471a810dad4086b5a0d2a7726a6584a3c5a0d2ed64cd60022f40928" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-05-12T06:36:37Z" +diff_format = "unified" +context_files = [ + "data/web/js/site/queue.js", + "data/web/templates/edit/filter.twig", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 15 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.451005+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:9e57425b07d152c34fd125e9de625f7d72d182e265f4e676323463e2f90807aa" +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-7220/tests/capture.py b/tasks/mailcow__mailcow-dockerized-7220/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7220/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture 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-7220/tests/instruction.md b/tasks/mailcow__mailcow-dockerized-7220/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3c0bb31feff077324cabcec3d6abd23bb62de7eb --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7220/tests/instruction.md @@ -0,0 +1,26 @@ +# Issue + +**Title:** [Web] escape HTML in sieve filter edit view and queue manager + +## 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 + +Two small UI fixes that align user-controlled values with the auto-escaping pattern already used elsewhere: + +- `edit/filter.twig`: drop `|raw` on `script_data`. +- `js/site/queue.js`: route `queue_id`, `queue_name`, `sender` through the DataTables text renderer; HTML-escape `queue_id` in the inline checkbox and action link. + +### Affected Containers + +- php-fpm-mailcow + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `539c32d99c66`. Edit files in place; the verifier captures your changes via `git diff` 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-7220/tests/oracle.patch b/tasks/mailcow__mailcow-dockerized-7220/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..b44b3afe55b2392450e27ecfc2ac4cf477960e94 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7220/tests/oracle.patch @@ -0,0 +1,60 @@ +diff --git a/data/web/js/site/queue.js b/data/web/js/site/queue.js +index 26c15091..9adc79b5 100644 +--- a/data/web/js/site/queue.js ++++ b/data/web/js/site/queue.js +@@ -48,13 +48,13 @@ jQuery(function($){ + url: "/api/v1/get/mailq/all", + dataSrc: function(data){ + $.each(data, function (i, item) { +- item.chkbox = ''; ++ item.chkbox = ''; + rcpts = $.map(item.recipients, function(i) { + return escapeHtml(i); + }); + item.recipients = rcpts.join('
'); + item.action = ''; + }); + return data; +@@ -79,12 +79,14 @@ jQuery(function($){ + { + title: 'QID', + data: 'queue_id', +- defaultContent: '' ++ defaultContent: '', ++ render: $.fn.dataTable.render.text() + }, + { + title: 'Queue', + data: 'queue_name', +- defaultContent: '' ++ defaultContent: '', ++ render: $.fn.dataTable.render.text() + }, + { + title: lang_admin.arrival_time, +@@ -106,7 +108,8 @@ jQuery(function($){ + { + title: lang_admin.sender, + data: 'sender', +- defaultContent: '' ++ defaultContent: '', ++ render: $.fn.dataTable.render.text() + }, + { + title: lang_admin.recipients, +diff --git a/data/web/templates/edit/filter.twig b/data/web/templates/edit/filter.twig +index 124ecaf7..743f088b 100644 +--- a/data/web/templates/edit/filter.twig ++++ b/data/web/templates/edit/filter.twig +@@ -23,7 +23,7 @@ +
+ +
+- ++ +
+
+
diff --git a/tasks/mailcow__mailcow-dockerized-7220/tests/test.sh b/tasks/mailcow__mailcow-dockerized-7220/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b0e1cb88b0888e2f4e23df6b99260be2c04c9cb8 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7220/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 539c32d99c665e64afb4a3baf7f6372b2494cd4f > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "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-7220/tests/verifier.py b/tasks/mailcow__mailcow-dockerized-7220/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7220/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "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-7224/environment/Dockerfile b/tasks/mailcow__mailcow-dockerized-7224/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..17ae27d505d1ebc430dcb3f71d3a5199b85490f2 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7224/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git 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 a8e945f3da89b98258a01b5137ca1a9dc72d67d9 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard a8e945f3da89b98258a01b5137ca1a9dc72d67d9 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base a8e945f3da89b98258a01b5137ca1a9dc72d67d9 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -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-7224/instruction.md b/tasks/mailcow__mailcow-dockerized-7224/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8f716493e8287e127d87f91eccf1958142bd5526 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7224/instruction.md @@ -0,0 +1,51 @@ +# Issue + +**Title:** Add Uzbek language + +## 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 Uzbek (Oʻzbekcha) as a new UI language for mailcow. + +- Registers `uz-uz => Oʻzbekcha (Uzbek)` in `$AVAILABLE_LANGUAGES` (`data/web/inc/vars.inc.php`), placed alphabetically after `uk-ua`. +- Adds a full translation file `data/web/lang/lang.uz-uz.json` covering all 23 top-level sections and all 1386 translatable strings from `lang.en-gb.json`. + +Notes on the translation: +- Uses modern Uzbek Latin script (the official script of Uzbekistan since 1993), including the proper `oʻ` / `gʻ` characters (e.g. `Oʻzbekcha`, `qoʻshish`). +- Preserves all JSON keys, HTML markup, format specifiers (`%s`, `%d`), placeholders (`{{var}}`, `_START_`, `_END_`, `_TOTAL_`, `_MAX_`, `_MENU_`), and ``/``/`` blocks unchanged. +- Technical terms (DKIM, DMARC, TLS, SMTP, IMAP, MX, OAuth2, Rspamd, SOGo, Fail2ban, FIDO2, WebAuthn, TOTP, etc.) are left untranslated to match common Uzbek IT usage. + +### Affected Containers + +- nginx-mailcow (UI/PHP files served by the web container only — no other container modified) + +## Did you run tests? + +### What did you tested? + +- Validated `lang.uz-uz.json` syntax with `jq empty` — file parses cleanly. +- Compared all top-level section keys between `lang.en-gb.json` and `lang.uz-uz.json` (`acl`, `add`, `admin`, `danger`, `datatables`, `debug`, `diagnostics`, `edit`, `fido2`, `footer`, `header`, `info`, `login`, `mailbox`, `oauth2`, `quarantine`, `queue`, `ratelimit`, `start`, `success`, `tfa`, `user`, `warning`) — `diff` reports no difference. +- Compared every sub-key inside each section against the English file — no missing or extra keys. +- Counted translatable string leaves with `jq` — both files have **1386** string entries. +- Verified that placeholders and HTML markup were preserved (no stripped ``, ``, ``, `%s`, `%d`, `{{...}}` tokens). +- Confirmed `vars.inc.php` change is a single-line addition matching the surrounding PHP array style; the language code follows the IETF tag convention used by the other entries. + +### What were the final results? (Awaited, got) + +- **Awaited:** New `uz-uz` option appears in the language switcher and the UI displays Uzbek strings when selected; existing locales continue to work unchanged. +- **Got:** JSON validation passes, key parity with `en-gb` is 1:1, and `vars.inc.php` cleanly registers the new locale. No regressions expected in other languages since only an additive change to `$AVAILABLE_LANGUAGES` and a new translation file are introduced. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `a8e945f3da89`. Edit files in place; the verifier captures your changes via `git diff` 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-7224/solution/patch.diff b/tasks/mailcow__mailcow-dockerized-7224/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..149d4fb8498ddaadd8afa920e58a108633839f5d --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7224/solution/patch.diff @@ -0,0 +1,1458 @@ +diff --git a/data/web/inc/vars.inc.php b/data/web/inc/vars.inc.php +index 2f4a4b07..cec402a9 100644 +--- a/data/web/inc/vars.inc.php ++++ b/data/web/inc/vars.inc.php +@@ -112,6 +112,7 @@ $AVAILABLE_LANGUAGES = array( + 'sv-se' => 'Svenska (Swedish)', + 'tr-tr' => 'Türkçe (Turkish)', + 'uk-ua' => 'Українська (Ukrainian)', ++ 'uz-uz' => 'Oʻzbekcha (Uzbek)', + 'vi-vn' => 'Tiếng Việt (Vietnamese)', + 'zh-cn' => '简体中文 (Simplified Chinese)', + 'zh-tw' => '繁體中文 (Traditional Chinese)', +diff --git a/data/web/lang/lang.uz-uz.json b/data/web/lang/lang.uz-uz.json +new file mode 100644 +index 00000000..a8d2ecf8 +--- /dev/null ++++ b/data/web/lang/lang.uz-uz.json +@@ -0,0 +1,1440 @@ ++{ ++ "acl": { ++ "alias_domains": "Taxallus domenlarini qoʻshish", ++ "app_passwds": "Ilova parollarini boshqarish", ++ "bcc_maps": "BCC xaritalari", ++ "delimiter_action": "Ajratuvchi amali", ++ "domain_desc": "Domen tavsifini oʻzgartirish", ++ "domain_relayhost": "Domen uchun relay xostni oʻzgartirish", ++ "eas_reset": "EAS qurilmalarini tiklash", ++ "extend_sender_acl": "Tashqi manzillar yordamida joʻnatuvchi ACL ni kengaytirishga ruxsat berish", ++ "filters": "Filtrlar", ++ "login_as": "Pochta qutisi foydalanuvchisi sifatida kirish", ++ "mailbox_relayhost": "Pochta qutisi uchun relay xostni oʻzgartirish", ++ "prohibited": "ACL tomonidan taqiqlangan", ++ "protocol_access": "Protokolga kirishni oʻzgartirish", ++ "pushover": "Pushover", ++ "pw_reset": "mailcow foydalanuvchi parolini tiklashga ruxsat berish", ++ "quarantine": "Karantin amallari", ++ "quarantine_attachments": "Karantindagi ilovalar", ++ "quarantine_category": "Karantin bildirishnoma turkumini oʻzgartirish", ++ "quarantine_notification": "Karantin bildirishnomalarini oʻzgartirish", ++ "ratelimit": "Tezlik chegarasi", ++ "recipient_maps": "Qabul qiluvchi xaritalari", ++ "smtp_ip_access": "SMTP uchun ruxsat etilgan xostlarni oʻzgartirish", ++ "sogo_access": "SOGo kirishini boshqarishga ruxsat berish", ++ "sogo_profile_reset": "SOGo profilini tiklash", ++ "spam_alias": "Vaqtinchalik taxalluslar", ++ "spam_policy": "Qora roʻyxat/Oq roʻyxat", ++ "spam_score": "Spam bahosi", ++ "syncjobs": "Sinxronizatsiya vazifalari", ++ "tls_policy": "TLS siyosati", ++ "unlimited_quota": "Pochta qutilari uchun cheksiz kvota" ++ }, ++ "add": { ++ "activate_filter_warn": "Faol belgilansa, boshqa barcha filtrlar oʻchirib qoʻyiladi.", ++ "active": "Faol", ++ "add": "Qoʻshish", ++ "add_domain_only": "Faqat domen qoʻshish", ++ "add_domain_restart": "Domen qoʻshish va SOGoni qayta ishga tushirish", ++ "alias_address": "Taxallus manzil(lar)i", ++ "alias_address_info": "Toʻliq e-pochta manzil(lar)i yoki @example.com — domenga keladigan barcha xabarlarni qabul qilish uchun (vergul bilan ajratilgan). Faqat mailcow domenlari.", ++ "alias_domain": "Taxallus domeni", ++ "alias_domain_info": "Faqat haqiqiy domen nomlari (vergul bilan ajratilgan).", ++ "app_name": "Ilova nomi", ++ "app_password": "Ilova paroli qoʻshish", ++ "app_passwd_protocols": "Ilova paroli uchun ruxsat etilgan protokollar", ++ "automap": "Papkalarni avtomatik xaritalashga harakat qilish (\"Sent items\", \"Sent\" => \"Sent\" va h.k.)", ++ "backup_mx_options": "Relay sozlamalari", ++ "bcc_dest_format": "BCC manzili bitta haqiqiy e-pochta manzili boʻlishi kerak.
Agar bir nechta manzilga nusxa joʻnatish kerak boʻlsa, taxallus yarating va shu yerda ishlating.", ++ "comment_info": "Maxfiy izoh foydalanuvchiga koʻrinmaydi, ommaviy izoh esa foydalanuvchi koʻrinishida ustiga sichqoncha kelganda maslahat sifatida koʻrsatiladi", ++ "custom_params": "Maxsus parametrlar", ++ "custom_params_hint": "Toʻgʻri: --param=xy, notoʻgʻri: --param xy", ++ "delete1": "Tugatilgach manbadan oʻchirish", ++ "delete2": "Manbada boʻlmagan xabarlarni manzildan oʻchirish", ++ "delete2duplicates": "Manzildagi dublikatlarni oʻchirish", ++ "description": "Tavsif", ++ "destination": "Manzil", ++ "disable_login": "Kirishni taqiqlash (kiruvchi pochta hali ham qabul qilinadi)", ++ "domain": "Domen", ++ "domain_matches_hostname": "%s domeni xost nomiga mos keladi", ++ "domain_quota_m": "Domenning umumiy kvotasi (MiB)", ++ "dry": "Sinxronizatsiyani simulyatsiya qilish", ++ "enc_method": "Shifrlash usuli", ++ "exclude": "Obyektlarni istisno qilish (regex)", ++ "full_name": "Toʻliq ism", ++ "gal": "Global manzillar roʻyxati", ++ "gal_info": "GAL domenning barcha obyektlarini oʻz ichiga oladi va hech bir foydalanuvchi tomonidan tahrirlanmaydi. Oʻchirilsa, SOGodagi bandlik maʼlumotlari yoʻqoladi! Oʻzgarishlarni qoʻllash uchun SOGoni qayta ishga tushiring.", ++ "generate": "yaratish", ++ "goto_ham": "ham sifatida oʻrgatish", ++ "goto_null": "Xatni jimgina rad etish", ++ "goto_spam": "spam sifatida oʻrgatish", ++ "hostname": "Xost", ++ "inactive": "Nofaol", ++ "internal": "Ichki", ++ "internal_info": "Ichki taxalluslarga faqat oʻz domeni yoki taxallus domenlaridan kirish mumkin.", ++ "sender_allowed": "Ushbu taxallus orqali joʻnatishga ruxsat berish", ++ "kind": "Turi", ++ "mailbox_quota_def": "Standart pochta qutisi kvotasi", ++ "mailbox_quota_m": "Bitta pochta qutisining maks. kvotasi (MiB)", ++ "mailbox_username": "Foydalanuvchi nomi (e-pochta manzilining chap qismi)", ++ "max_aliases": "Mumkin boʻlgan maks. taxalluslar", ++ "max_mailboxes": "Mumkin boʻlgan maks. pochta qutilari", ++ "mins_interval": "Soʻrov oraligʻi (daqiqa)", ++ "multiple_bookings": "Bir nechta bandlovlar", ++ "nexthop": "Keyingi nuqta", ++ "password": "Parol", ++ "password_repeat": "Tasdiqlash paroli (takrorlang)", ++ "port": "Port", ++ "post_domain_add": "Yangi domen qoʻshilgandan keyin SOGo konteyneri (\"sogo-mailcow\") qayta ishga tushirilishi kerak!

Bundan tashqari, domenning DNS sozlamalarini koʻrib chiqing. DNS sozlamalari tasdiqlangach, yangi domeningiz (autoconfig.<domain>, autodiscover.<domain>) uchun sertifikatlarni avtomatik yaratish uchun \"acme-mailcow\" konteynerini qayta ishga tushiring.
Bu qadam ixtiyoriy va har 24 soatda qayta urinib koʻriladi.", ++ "private_comment": "Maxfiy izoh", ++ "public_comment": "Ommaviy izoh", ++ "quota_mb": "Kvota (MiB)", ++ "relay_all": "Barcha qabul qiluvchilarni relay qilish", ++ "relay_all_info": "↪ Agar barcha qabul qiluvchilarni relay qilmaslikni tanlasangiz, relay qilinishi kerak boʻlgan har bir qabul qiluvchi uchun (\"koʻr\") pochta qutisi qoʻshishingiz kerak boʻladi.", ++ "relay_domain": "Ushbu domenni relay qilish", ++ "relay_transport_info": "
Maʼlumot
Bu domen uchun maxsus manzilga transport xaritalarini belgilashingiz mumkin. Agar oʻrnatilmagan boʻlsa, MX qidiruvi amalga oshiriladi.", ++ "relay_unknown_only": "Faqat mavjud boʻlmagan pochta qutilarini relay qilish. Mavjud pochta qutilari mahalliy yetkazib beriladi.", ++ "relayhost_wrapped_tls_info": "Iltimos, TLS-oʻralgan portlardan foydalanmang (asosan 465-portda).
\r\nO'ralmagan istalgan portdan foydalaning va STARTTLS chiqaring. TLS ni majburlash uchun TLS siyosatini \"TLS siyosati xaritalari\"da yaratish mumkin.", ++ "select": "Iltimos, tanlang...", ++ "select_domain": "Avval domenni tanlang", ++ "sieve_desc": "Qisqa tavsif", ++ "sieve_type": "Filtr turi", ++ "skipcrossduplicates": "Papkalararo dublikat xabarlarni oʻtkazib yuborish (birinchi kelgan, birinchi xizmatlanadi)", ++ "subscribeall": "Barcha papkalarga obuna boʻlish", ++ "syncjob": "Sinxronizatsiya vazifasi qoʻshish", ++ "syncjob_hint": "Parollar oddiy matn sifatida saqlanishini unutmang!", ++ "tags": "Teglar", ++ "target_address": "Yoʻnaltirish manzillari", ++ "target_address_info": "Toʻliq e-pochta manzil(lar)i (vergul bilan ajratilgan).", ++ "target_domain": "Maqsad domen", ++ "timeout1": "Masofaviy xostga ulanish vaqtining tugashi", ++ "timeout2": "Mahalliy xostga ulanish vaqtining tugashi", ++ "username": "Foydalanuvchi nomi", ++ "validate": "Tekshirish", ++ "validation_success": "Muvaffaqiyatli tekshirildi" ++ }, ++ "admin": { ++ "access": "Kirish", ++ "action": "Amal", ++ "activate_api": "API ni faollashtirish", ++ "activate_send": "Joʻnatish tugmasini faollashtirish", ++ "active": "Faol", ++ "active_rspamd_settings_map": "Faol sozlamalar xaritasi", ++ "add": "Qoʻshish", ++ "add_admin": "Administrator qoʻshish", ++ "add_domain_admin": "Domen administratorini qoʻshish", ++ "add_forwarding_host": "Yoʻnaltirish xosti qoʻshish", ++ "add_relayhost": "Joʻnatuvchiga bogʻliq transport qoʻshish", ++ "add_relayhost_hint": "Autentifikatsiya maʼlumotlari, agar boʻlsa, oddiy matn sifatida saqlanishini unutmang.", ++ "add_row": "Satr qoʻshish", ++ "add_settings_rule": "Sozlamalar qoidasini qoʻshish", ++ "add_transport": "Transport qoʻshish", ++ "add_transports_hint": "Autentifikatsiya maʼlumotlari, agar boʻlsa, oddiy matn sifatida saqlanishini unutmang.", ++ "additional_rows": " ta qoʻshimcha satr qoʻshildi", ++ "admin": "Administrator", ++ "admin_details": "Administrator maʼlumotlarini tahrirlash", ++ "admin_domains": "Domen tayinlashlari", ++ "admins": "Administratorlar", ++ "admins_ldap": "LDAP administratorlari", ++ "admin_quicklink": "Admin kirish sahifasiga tezkor havolani yashirish", ++ "advanced_settings": "Kengaytirilgan sozlamalar", ++ "allowed_methods": "Access-Control-Allow-Methods", ++ "allowed_origins": "Access-Control-Allow-Origin", ++ "api_allow_from": "API kirishini ushbu IP / CIDR tarmoq belgilanishlaridan ruxsat berish", ++ "api_info": "API ishlab chiqilmoqda. Hujjatlarni
/api manzilida topishingiz mumkin", ++ "api_key": "API kaliti", ++ "api_read_only": "Faqat oʻqish uchun kirish", ++ "api_read_write": "Oʻqish va yozish uchun kirish", ++ "api_skip_ip_check": "API uchun IP tekshiruvini oʻtkazib yuborish", ++ "app_hide": "Kirishda yashirish", ++ "app_links": "Ilova havolalari", ++ "app_name": "Ilova nomi", ++ "apps_name": "\"mailcow Apps\" nomi", ++ "arrival_time": "Kelish vaqti (server vaqti)", ++ "authed_user": "Avtorizatsiya qilingan foydalanuvchi", ++ "ays": "Davom etishni xohlayotganingizga ishonchingiz komilmi?", ++ "ban_list_info": "Quyida bloklangan IP roʻyxati keltirilgan: tarmoq (qolgan blok vaqti) - [amallar].
Blokdan chiqarishga navbatga qoʻyilgan IP lar bir necha soniya ichida faol bloklash roʻyxatidan olib tashlanadi.
Qizil yorliqlar qora roʻyxat orqali faol doimiy bloklarni bildiradi.", ++ "change_logo": "Logotipni oʻzgartirish", ++ "logo_normal_label": "Oddiy", ++ "logo_dark_label": "Qorongʻi rejim uchun teskari", ++ "configuration": "Konfiguratsiya", ++ "convert_html_to_text": "HTMLni oddiy matnga aylantirish", ++ "copy_to_clipboard": "Matn vaqtinchalik xotiraga koʻchirildi!", ++ "cors_settings": "CORS sozlamalari", ++ "credentials_transport_warning": "Diqqat: Yangi transport xaritasi yozuvi qoʻshish keyingi nuqta ustunlari mos keladigan barcha yozuvlar uchun maʼlumotlarni yangilaydi.", ++ "customer_id": "Mijoz ID", ++ "customize": "Sozlash", ++ "login_page": "Kirish sahifasi", ++ "destination": "Manzil", ++ "dkim_add_key": "ARC/DKIM kaliti qoʻshish", ++ "dkim_domains_selector": "Tanlovchi", ++ "dkim_domains_wo_keys": "Kalit yetishmaydigan domenlarni tanlash", ++ "dkim_from": "Kimdan", ++ "dkim_from_title": "Maʼlumotlarni koʻchirib olish uchun manba domen", ++ "dkim_key_length": "DKIM kalit uzunligi (bit)", ++ "dkim_key_missing": "Kalit yetishmaydi", ++ "dkim_key_unused": "Kalit ishlatilmagan", ++ "dkim_key_valid": "Kalit haqiqiy", ++ "dkim_keys": "ARC/DKIM kalitlari", ++ "dkim_overwrite_key": "Mavjud DKIM kalitini ustidan yozish", ++ "dkim_private_key": "Maxfiy kalit", ++ "dkim_to": "Kimga", ++ "dkim_to_title": "Maqsad domen(lar) — ustidan yoziladi", ++ "domain": "Domen", ++ "domain_admin": "Domen administratori", ++ "domain_admins": "Domen administratorlari", ++ "domainadmin_quicklink": "Domen admin kirish sahifasiga tezkor havolani yashirish", ++ "domain_s": "Domen(lar)", ++ "duplicate": "Nusxalash", ++ "duplicate_dkim": "DKIM yozuvini nusxalash", ++ "edit": "Tahrirlash", ++ "empty": "Natijalar yoʻq", ++ "excludes": "Ushbu qabul qiluvchilarni istisno qiladi", ++ "f2b_ban_time": "Bloklash vaqti (s)", ++ "f2b_ban_time_increment": "Har bir bloklashda blok vaqti ortadi", ++ "f2b_blacklist": "Qora roʻyxatdagi tarmoqlar/xostlar", ++ "f2b_filter": "Regex filtrlari", ++ "f2b_list_info": "Qora roʻyxatdagi xost yoki tarmoq har doim oq roʻyxat elementidan ustun keladi. Roʻyxat yangilanishlarini qoʻllash uchun bir necha soniya kerak boʻladi.", ++ "f2b_manage_external": "Fail2ban ni tashqi boshqarish", ++ "f2b_manage_external_info": "Fail2ban hali ham banlist ni saqlaydi, ammo trafikni bloklash uchun faol qoidalarni oʻrnatmaydi. Trafikni tashqi tomondan bloklash uchun quyida yaratilgan banlist dan foydalaning.", ++ "f2b_max_attempts": "Maks. urinishlar", ++ "f2b_max_ban_time": "Maks. bloklash vaqti (s)", ++ "f2b_netban_ipv4": "Blokni qoʻllash uchun IPv4 subtarmoq oʻlchami (8-32)", ++ "f2b_netban_ipv6": "Blokni qoʻllash uchun IPv6 subtarmoq oʻlchami (8-128)", ++ "f2b_parameters": "Fail2ban parametrlari", ++ "f2b_regex_info": "Eʼtiborga olinadigan jurnallar: SOGo, Postfix, Dovecot, PHP-FPM.", ++ "f2b_retry_window": "Maks. urinishlar uchun qayta urinish oynasi (s)", ++ "f2b_whitelist": "Oq roʻyxatdagi tarmoqlar/xostlar", ++ "filter": "Filtr", ++ "filter_table": "Filtr jadvali", ++ "force_sso_text": "Tashqi OIDC provayder sozlangan boʻlsa, bu variant standart mailcow kirish formalarini yashiradi va faqat Yagona kirish tugmasini koʻrsatadi", ++ "force_sso": "mailcow kirishini oʻchirib, faqat Yagona kirishni koʻrsatish", ++ "forwarding_hosts": "Yoʻnaltirish xostlari", ++ "forwarding_hosts_add_hint": "Siz IPv4/IPv6 manzillarini, CIDR yozuvidagi tarmoqlarni, xost nomlarini (IP manzillariga aylantiriladi) yoki domen nomlarini (SPF TXT yoki yoʻq boʻlsa MX yozuvlarini soʻrash orqali IP manzillariga aylantiriladi) belgilashingiz mumkin.", ++ "forwarding_hosts_hint": "Kiruvchi xabarlar bu yerda keltirilgan istalgan xostlardan shartsiz qabul qilinadi. Bu xostlar keyin DNSBL ga qarshi tekshirilmaydi yoki greylisting ga olinmaydi. Ulardan kelgan spam hech qachon rad etilmaydi, ammo ixtiyoriy ravishda Junk papkasiga joylashtirilishi mumkin. Buning eng keng tarqalgan ishlatilishi — mailcow serveringizga kiruvchi xatlarni yoʻnaltirish qoidasi oʻrnatilgan pochta serverlarini koʻrsatish.", ++ "from": "Kimdan", ++ "generate": "yaratish", ++ "guid": "GUID - noyob nusxa ID si", ++ "guid_and_license": "GUID va litsenziya", ++ "hash_remove_info": "Ratelimit hashini oʻchirish (agar mavjud boʻlsa) uning hisoblagichini butunlay tiklaydi.
\r\n Har bir hash alohida rang bilan koʻrsatiladi.", ++ "help_text": "Kirish maskasi ostidagi yordam matnini bekor qilish (HTML ruxsat etilgan)", ++ "host": "Xost", ++ "html": "HTML", ++ "iam": "Identifikatsiya provayderi", ++ "iam_attribute_field": "Atribut maydoni", ++ "iam_authorize_url": "Avtorizatsiya nuqtasi", ++ "iam_auth_flow": "Autentifikatsiya oqimi", ++ "iam_auth_flow_info": "Yagona kirish (SSO) uchun ishlatiladigan Authorization Code Flow (Keycloak da Standard Flow) qoʻshimcha ravishda, mailcow toʻgʻridan-toʻgʻri maʼlumotlar bilan Autentifikatsiya oqimini ham qoʻllab-quvvatlaydi. Mailpassword Flow Keycloak Admin REST API yordamida foydalanuvchi maʼlumotlarini tekshirishga harakat qiladi. mailcow Keycloakda xaritalangan mailcow_password atributidan xeshlangan parolni oladi.", ++ "iam_basedn": "Base DN", ++ "iam_client_id": "Mijoz ID", ++ "iam_client_secret": "Mijoz maxfiy soʻzi", ++ "iam_client_scopes": "Mijoz qamrovlari", ++ "iam_default_template": "Standart shablon", ++ "iam_default_template_description": "Agar foydalanuvchiga shablon tayinlanmagan boʻlsa, pochta qutisini yaratishda standart shablon ishlatiladi, lekin pochta qutisini yangilash uchun emas.", ++ "iam_description": "Autentifikatsiya uchun tashqi provayderni sozlash
Foydalanuvchi pochta qutilari atribut xaritalashi oʻrnatilgan boʻlsa, ular birinchi marta kirgan zahoti avtomatik yaratiladi.", ++ "iam_extra_permission": "Quyidagi sozlamalarning ishlashi uchun Keycloak dagi mailcow mijoziga Service account va view-users ruxsati kerak.", ++ "iam_host": "Xost", ++ "iam_host_info": "Bir yoki bir nechta LDAP xostni vergul bilan ajratib kiriting.", ++ "iam_import_users": "Foydalanuvchilarni import qilish", ++ "iam_login_provisioning": "Kirishda foydalanuvchilarni avto-yaratish", ++ "iam_mapping": "Atribut xaritalashi", ++ "iam_bindpass": "Bind paroli", ++ "iam_periodic_full_sync": "Davriy toʻliq sinxronizatsiya", ++ "iam_port": "Port", ++ "iam_realm": "Realm", ++ "iam_redirect_url": "Yoʻnaltirish URL", ++ "iam_rest_flow": "Mailpassword Flow", ++ "iam_server_url": "Server URL", ++ "iam_sso": "Yagona kirish (SSO)", ++ "iam_sync_interval": "Sinxronizatsiya / import oraligʻi (daqiqa)", ++ "iam_test_connection": "Ulanishni tekshirish", ++ "iam_token_url": "Token nuqtasi", ++ "iam_userinfo_url": "Foydalanuvchi maʼlumotlari nuqtasi", ++ "iam_username_field": "Foydalanuvchi nomi maydoni", ++ "iam_binddn": "Bind DN", ++ "iam_use_ssl": "SSL dan foydalanish", ++ "iam_use_ssl_info": "SSL yoqilsa va port 389 ga oʻrnatilgan boʻlsa, u avtomatik ravishda 636 ga oʻzgartiriladi.", ++ "iam_use_tls": "StartTLS dan foydalanish", ++ "iam_use_tls_info": "TLS yoqilsa, LDAP serveringiz uchun standart portni (389) ishlatishingiz kerak. SSL portlari ishlatilmaydi.", ++ "iam_version": "Versiya", ++ "ignore_ssl_error": "SSL xatolarini eʼtiborsiz qoldirish", ++ "import": "Import", ++ "import_private_key": "Maxfiy kalitni import qilish", ++ "in_use_by": "Kim ishlatadi", ++ "inactive": "Nofaol", ++ "include_exclude": "Kiritish/Istisno qilish", ++ "include_exclude_info": "Standart holatda — tanlovsiz — barcha pochta qutilariga murojaat qilinadi", ++ "includes": "Ushbu qabul qiluvchilarni kiritish", ++ "ip_check": "IP tekshiruvi", ++ "ip_check_disabled": "IP tekshiruvi oʻchirilgan. Uni quyidagi joydan yoqishingiz mumkin:
Tizim > Konfiguratsiya > Variantlar > Sozlash", ++ "ip_check_opt_in": "Tashqi IP manzillarni aniqlash uchun ipv4.mailcow.email va ipv6.mailcow.email uchinchi tomon xizmatidan foydalanishga rozilik.", ++ "is_mx_based": "MX asosida", ++ "last_applied": "Oxirgi qoʻllanilgan", ++ "license_info": "Litsenziya talab qilinmaydi, ammo bu loyihaning rivojlanishiga yordam beradi.
GUID ni bu yerda roʻyxatdan oʻtkazing yoki mailcow oʻrnatmangiz uchun yordam sotib oling.", ++ "link": "Havola", ++ "loading": "Iltimos, kuting...", ++ "login_time": "Kirish vaqti", ++ "logo_info": "Tasviringiz yuqori navigatsiya paneli uchun 40px balandlikka, bosh sahifa uchun maks. 250px kenglikka oʻlchanadi. Masshtablanadigan grafika tavsiya etiladi.", ++ "lookup_mx": "Manzil — MX nomiga mos keladigan muntazam ifoda (.*\\.google\\.com — google.com bilan tugaydigan MX ga yoʻnaltirilgan barcha pochtani ushbu nuqta orqali yoʻnaltirish uchun)", ++ "main_name": "\"mailcow UI\" nomi", ++ "merged_vars_hint": "Kulrang satrlar vars.(local.)inc.php dan birlashtirilgan va oʻzgartirib boʻlmaydi.", ++ "message": "Xabar", ++ "message_size": "Xabar oʻlchami", ++ "nexthop": "Keyingi nuqta", ++ "needs_restart": "qayta ishga tushirish kerak", ++ "no": "✕", ++ "no_active_bans": "Faol bloklar yoʻq", ++ "no_new_rows": "Boshqa satrlar mavjud emas", ++ "no_record": "Yozuv yoʻq", ++ "oauth2_apps": "OAuth2 ilovalari", ++ "oauth2_add_client": "OAuth2 mijozini qoʻshish", ++ "oauth2_client_id": "Mijoz ID", ++ "oauth2_client_secret": "Mijoz maxfiy soʻzi", ++ "oauth2_info": "OAuth2 amalga oshirilishi \"Authorization Code\" grant turini qoʻllab-quvvatlaydi va refresh tokenlarini chiqaradi.
\r\nServer shuningdek refresh token ishlatilgandan keyin avtomatik ravishda yangi refresh tokenlarini chiqaradi.

\r\n• Standart qamrov — profile. Faqat pochta qutisi foydalanuvchilari OAuth2 ga qarshi autentifikatsiya qilinishi mumkin. Agar scope parametri tashlab ketilgan boʻlsa, u profile ga qaytadi.
\r\n• state parametri mijoz tomonidan avtorizatsiya soʻrovining bir qismi sifatida yuborilishi shart.

\r\nOAuth2 API ga soʻrovlar uchun yoʻllar:
\r\n
    \r\n
  • Avtorizatsiya nuqtasi: /oauth/authorize
  • \r\n
  • Token nuqtasi: /oauth/token
  • \r\n
  • Resurs sahifasi: /oauth/profile
  • \r\n
\r\nMijoz maxfiy soʻzini qayta yaratish mavjud avtorizatsiya kodlarini muddati tugashiga olib kelmaydi, lekin ular tokenni yangilashda muvaffaqiyatsiz boʻladi.

\r\nMijoz tokenlarini bekor qilish barcha faol sessiyalarning darhol tugashiga olib keladi. Barcha mijozlar qayta autentifikatsiya qilishlari kerak.", ++ "oauth2_redirect_uri": "Yoʻnaltirish URI", ++ "oauth2_renew_secret": "Yangi mijoz maxfiy soʻzini yaratish", ++ "oauth2_revoke_tokens": "Barcha mijoz tokenlarini bekor qilish", ++ "optional": "ixtiyoriy", ++ "options": "Variantlar", ++ "password": "Parol", ++ "password_length": "Parol uzunligi", ++ "password_policy": "Parol siyosati", ++ "password_policy_chars": "Kamida bitta alifbo belgisini oʻz ichiga olishi kerak", ++ "password_policy_length": "Minimal parol uzunligi %d", ++ "password_policy_lowerupper": "Kichik va katta harflarni oʻz ichiga olishi kerak", ++ "password_policy_numbers": "Kamida bitta raqamni oʻz ichiga olishi kerak", ++ "password_policy_special_chars": "Maxsus belgilarni oʻz ichiga olishi kerak", ++ "password_repeat": "Tasdiqlash paroli (takrorlang)", ++ "password_reset_info": "Agar tiklash uchun e-pochta kiritilmagan boʻlsa, bu funksiyadan foydalanib boʻlmaydi.", ++ "password_reset_settings": "Parolni tiklash sozlamalari", ++ "password_reset_tmpl_html": "HTML shablon", ++ "password_reset_tmpl_text": "Matnli shablon", ++ "password_settings": "Parol sozlamalari", ++ "priority": "Muhimlik darajasi", ++ "private_key": "Maxfiy kalit", ++ "quarantine": "Karantin", ++ "quarantine_bcc": "Barcha bildirishnomalarning nusxasini (BCC) ushbu qabul qiluvchiga yuborish:
Oʻchirish uchun boʻsh qoldiring. Imzolanmagan, tekshirilmagan xat. Faqat ichki yetkazib berilishi kerak.", ++ "quarantine_exclude_domains": "Domenlar va taxallus domenlarini istisno qilish", ++ "quarantine_max_age": "Maksimal yosh (kunlarda)
Qiymat 1 kun yoki undan koʻp boʻlishi kerak.", ++ "quarantine_max_score": "Agar xatning spam bahosi ushbu qiymatdan yuqori boʻlsa, bildirishnomani rad etish:
Standart 9999.0", ++ "quarantine_max_size": "Maksimal oʻlcham (MiB) (kattaroq elementlar rad etiladi):
0 cheksizlikni bildirmaydi.", ++ "quarantine_notification_html": "Bildirishnoma e-pochta shabloni:
Standart shablonni tiklash uchun boʻsh qoldiring.", ++ "quarantine_notification_sender": "Bildirishnoma e-pochta joʻnatuvchisi", ++ "quarantine_notification_subject": "Bildirishnoma e-pochta mavzusi", ++ "quarantine_redirect": "Barcha bildirishnomalarni ushbu qabul qiluvchiga yoʻnaltirish:
Oʻchirish uchun boʻsh qoldiring. Imzolanmagan, tekshirilmagan xat. Faqat ichki yetkazib berilishi kerak.", ++ "quarantine_release_format": "Chiqarilgan elementlar formati", ++ "quarantine_release_format_att": "Ilova sifatida", ++ "quarantine_release_format_raw": "Oʻzgartirilmagan asl nusxa", ++ "quarantine_retention_size": "Pochta qutisi uchun saqlash:
0 — nofaolligini bildiradi.", ++ "quicklink_text": "Boshqa kirish sahifalariga tezkor havolalarni kirish formasi ostida koʻrsatish yoki yashirish", ++ "quota_notification_html": "Bildirishnoma e-pochta shabloni:
Standart shablonni tiklash uchun boʻsh qoldiring.", ++ "quota_notification_sender": "Bildirishnoma e-pochta joʻnatuvchisi", ++ "quota_notification_subject": "Bildirishnoma e-pochta mavzusi", ++ "quota_notifications": "Kvota bildirishnomalari", ++ "quota_notifications_info": "Kvota bildirishnomalari foydalanuvchilarga foydalanish 80% va 95% ga yetganda bir martadan yuboriladi.", ++ "quota_notifications_vars": "{{percent}} — foydalanuvchining joriy kvotasi
{{username}} — pochta qutisi nomi", ++ "queue_unban": "blokdan chiqarish", ++ "r_active": "Faol cheklovlar", ++ "r_inactive": "Nofaol cheklovlar", ++ "r_info": "Faol cheklovlar roʻyxatidagi kulrang/oʻchirilgan elementlar mailcow uchun haqiqiy cheklovlar sifatida tanilmaydi va koʻchirib boʻlmaydi. Nomaʼlum cheklovlar baribir koʻrinish tartibida oʻrnatiladi.
inc/vars.local.inc.php da yangi elementlarni qoʻshib, ularni almashtirishingiz mumkin.", ++ "rate_name": "Tezlik nomi", ++ "recipients": "Qabul qiluvchilar", ++ "refresh": "Yangilash", ++ "regen_api_key": "API kalitini qayta yaratish", ++ "regex_maps": "Regex xaritalari", ++ "relay_from": "\"From:\" manzili", ++ "relay_rcpt": "\"To:\" manzili", ++ "relay_run": "Sinovni ishga tushirish", ++ "relayhosts": "Joʻnatuvchiga bogʻliq transportlar", ++ "relayhosts_hint": "Domen konfiguratsiya muloqotida tanlash mumkin boʻlgan joʻnatuvchiga bogʻliq transportlarni belgilang.
\r\n Transport xizmati har doim \"smtp:\" va shuning uchun taklif qilinganda TLS ga harakat qiladi. Oʻralgan TLS (SMTPS) qoʻllab-quvvatlanmaydi. Foydalanuvchining individual chiquvchi TLS siyosati sozlamasi eʼtiborga olinadi.
\r\n Taxallus domenlari bilan birga tanlangan domenlarga taʼsir qiladi.", ++ "remove": "Olib tashlash", ++ "remove_row": "Satrni olib tashlash", ++ "reset_default": "Standartga qaytarish", ++ "reset_limit": "Hash ni olib tashlash", ++ "reset_password_vars": "{{link}} Yaratilgan parolni tiklash havolasi
{{username}} Parolni tiklashni soʻragan foydalanuvchining pochta qutisi nomi
{{username2}} Tiklash uchun pochta qutisi nomi
{{date}} Parolni tiklash soʻrovi qilingan sana
{{token_lifetime}} Daqiqalardagi token muddati
{{hostname}} mailcow xost nomi", ++ "restore_template": "Standart shablonni tiklash uchun boʻsh qoldiring.", ++ "routing": "Yoʻnaltirish", ++ "rsetting_add_rule": "Qoida qoʻshish", ++ "rsetting_content": "Qoida mazmuni", ++ "rsetting_desc": "Qisqa tavsif", ++ "rsetting_no_selection": "Iltimos, qoidani tanlang", ++ "rsetting_none": "Qoidalar mavjud emas", ++ "rsettings_insert_preset": "Misol presetini kiritish \"%s\"", ++ "rsettings_preset_1": "Autentifikatsiya qilingan foydalanuvchilar uchun DKIM va tezlik chegarasidan boshqa hamma narsani oʻchirib qoʻyish", ++ "rsettings_preset_2": "Postmasterlar spamni xohlaydi", ++ "rsettings_preset_3": "Pochta qutisi uchun faqat maxsus joʻnatuvchilarga ruxsat berish (yaʼni, faqat ichki pochta qutisi sifatida ishlatish)", ++ "rsettings_preset_4": "Domen uchun Rspamd ni oʻchirish", ++ "rspamd_com_settings": "Sozlama nomi avtomatik yaratiladi, quyidagi misol presetlariga qarang. Batafsil maʼlumot uchun Rspamd hujjatlariga qarang", ++ "rspamd_global_filters": "Global filtr xaritalari", ++ "rspamd_global_filters_agree": "Ehtiyot boʻlaman!", ++ "rspamd_global_filters_info": "Global filtr xaritalari turli xil global rad etish va ruxsat berish roʻyxatlarini oʻz ichiga oladi.", ++ "rspamd_global_filters_regex": "Ularning nomlari ularning maqsadini tushuntiradi. Barcha mazmun \"/pattern/options\" formatidagi haqiqiy muntazam ifodalarni oʻz ichiga olishi kerak (masalan, /.+@domain\\.tld/i).
\r\n Har bir regex satriga oddiy tekshiruvlar bajariladi, ammo agar Rspamd sintaksisni toʻgʻri oʻqiy olmasa, uning funksionalligi buzilishi mumkin.
\r\n Rspamd oʻzgarganda xarita mazmunini oʻqishga harakat qiladi. Agar muammolarga duch kelsangiz, xarita qayta yuklanishi uchun Rspamd ni qayta ishga tushiring.
Qora roʻyxatdagi elementlar karantindan istisno qilinadi.", ++ "rspamd_settings_map": "Rspamd sozlamalar xaritasi", ++ "sal_level": "Moo darajasi", ++ "save": "Oʻzgarishlarni saqlash", ++ "search_domain_da": "Domenlarni qidirish", ++ "send": "Joʻnatish", ++ "sender": "Joʻnatuvchi", ++ "service": "Xizmat", ++ "service_id": "Xizmat ID", ++ "source": "Manba", ++ "spamfilter": "Spam filtri", ++ "subject": "Mavzu", ++ "success": "Muvaffaqiyatli", ++ "sys_mails": "Tizim xatlari", ++ "task": "Vazifa", ++ "text": "Matn", ++ "time": "Vaqt", ++ "title": "Sarlavha", ++ "title_name": "\"mailcow UI\" veb-sayt sarlavhasi", ++ "to_top": "Yuqoriga qaytish", ++ "transport_dest_format": "Regex yoki sintaksis: example.org, .example.org, *, box@example.org (bir nechta qiymatlarni vergul bilan ajratish mumkin)", ++ "transport_maps": "Transport xaritalari", ++ "transport_test_rcpt_info": "• Tashqi manzilga relay qilishni sinash uchun null@hosted.mailcow.de dan foydalaning.", ++ "transports_hint": "• Transport xaritasi yozuvi joʻnatuvchiga bogʻliq transport xaritasidan ustun.
\r\n• MX asosidagi transportlar afzalroq ishlatiladi.
\r\n• Foydalanuvchi boʻyicha chiquvchi TLS siyosati sozlamalari eʼtiborga olinmaydi va faqat TLS siyosati xaritasi yozuvlari orqali majburlanishi mumkin.
\r\n• Belgilangan transportlar uchun transport xizmati har doim \"smtp:\" va shuning uchun taklif qilinganda TLS ga harakat qiladi. Oʻralgan TLS (SMTPS) qoʻllab-quvvatlanmaydi.
\r\n• \"/localhost$/\" ga mos keladigan manzillar har doim \"local:\" orqali tashiladi, shuning uchun \"*\" manzili bu manzillarga qoʻllanmaydi.
\r\n• Misol uchun keyingi nuqta \"[host]:25\" uchun maʼlumotlarni aniqlash uchun, Postfix har doim \"[host]:25\" ni qidirishdan oldin \"host\" ni soʻraydi. Bu xatti-harakat \"host\" va \"[host]:25\" ni bir vaqtning oʻzida ishlatishni imkonsiz qiladi.", ++ "ui_footer": "Pastki qism (HTML ruxsat etilgan)", ++ "ui_header_announcement": "Eʼlonlar", ++ "ui_header_announcement_active": "Eʼlonni faollashtirish", ++ "ui_header_announcement_content": "Matn (HTML ruxsat etilgan)", ++ "ui_header_announcement_help": "Eʼlon barcha tizimga kirgan foydalanuvchilarga va UI ning kirish ekranida koʻrinadi.", ++ "ui_header_announcement_select": "Eʼlon turini tanlang", ++ "ui_header_announcement_type": "Tur", ++ "ui_header_announcement_type_danger": "Juda muhim", ++ "ui_header_announcement_type_info": "Maʼlumot", ++ "ui_header_announcement_type_warning": "Muhim", ++ "ui_texts": "UI yorliqlari va matnlari", ++ "unban_pending": "blokdan chiqarish kutilmoqda", ++ "unchanged_if_empty": "Oʻzgartirilmagan boʻlsa, boʻsh qoldiring", ++ "upload": "Yuklash", ++ "username": "Foydalanuvchi nomi", ++ "user_link": "Foydalanuvchi havolasi", ++ "user_quicklink": "Foydalanuvchi kirish sahifasiga tezkor havolani yashirish", ++ "validate_license_now": "GUID ni litsenziya serveriga qarshi tekshirish", ++ "verify": "Tasdiqlash", ++ "yes": "✓" ++ }, ++ "danger": { ++ "access_denied": "Kirish rad etildi yoki noma'lum forma ma'lumotlari", ++ "tfa_removal_blocked": "Ikki faktorli autentifikatsiyani olib tashlab boʻlmaydi, chunki u sizning hisobingiz uchun talab qilinadi.", ++ "alias_domain_invalid": "%s taxallus domeni noto'g'ri", ++ "alias_empty": "Taxallus manzili boʻsh boʻlmasligi kerak", ++ "alias_goto_identical": "Taxallus va yoʻnaltirish manzili bir xil boʻlmasligi kerak", ++ "alias_invalid": "%s taxallus manzili noto'g'ri", ++ "aliasd_targetd_identical": "Taxallus domeni maqsad domeniga teng boʻlmasligi kerak: %s", ++ "aliases_in_use": "Maks. taxalluslar %d dan katta yoki teng boʻlishi kerak", ++ "app_name_empty": "Ilova nomi boʻsh boʻlolmaydi", ++ "app_passwd_id_invalid": "Ilova paroli ID %s noto'g'ri", ++ "authsource_in_use": "Identifikatsiya provayderini oʻzgartirib yoki oʻchirib boʻlmaydi, chunki u hozirda bir yoki bir nechta foydalanuvchilar tomonidan ishlatilmoqda.", ++ "bcc_empty": "BCC manzili boʻsh boʻlolmaydi", ++ "bcc_exists": "%s turi uchun %s BCC xaritasi mavjud", ++ "bcc_must_be_email": "BCC manzili %s haqiqiy e-pochta manzili emas", ++ "comment_too_long": "Izoh juda uzun, maks. 160 ta belgiga ruxsat berilgan", ++ "cors_invalid_method": "Noto'g'ri Allow-Method belgilangan", ++ "cors_invalid_origin": "Noto'g'ri Allow-Origin belgilangan", ++ "defquota_empty": "Bitta pochta qutisi uchun standart kvota 0 boʻlmasligi kerak.", ++ "demo_mode_enabled": "Demo rejim yoqilgan", ++ "description_invalid": "%s uchun resurs tavsifi noto'g'ri", ++ "dkim_domain_or_sel_exists": "\"%s\" uchun DKIM kaliti mavjud va u ustidan yozilmaydi", ++ "dkim_domain_or_sel_invalid": "DKIM domeni yoki tanlovchi noto'g'ri: %s", ++ "domain_cannot_match_hostname": "Domen xost nomiga mos kelishi mumkin emas", ++ "domain_exists": "%s domeni allaqachon mavjud", ++ "domain_invalid": "Domen nomi boʻsh yoki noto'g'ri", ++ "domain_not_empty": "Boʻsh boʻlmagan %s domenini olib tashlab boʻlmaydi", ++ "domain_not_found": "%s domeni topilmadi", ++ "domain_quota_m_in_use": "Domen kvotasi %s MiB dan katta yoki teng boʻlishi kerak", ++ "extended_sender_acl_denied": "Tashqi joʻnatuvchi manzillarini oʻrnatish uchun ACL yetishmayapti", ++ "extra_acl_invalid": "Tashqi joʻnatuvchi manzili \"%s\" noto'g'ri", ++ "extra_acl_invalid_domain": "Tashqi joʻnatuvchi \"%s\" noto'g'ri domendan foydalanmoqda", ++ "fido2_verification_failed": "FIDO2 tekshiruvi muvaffaqiyatsiz: %s", ++ "file_open_error": "Faylni yozish uchun ochib boʻlmadi", ++ "filter_type": "Notoʻgʻri filtr turi", ++ "from_invalid": "Joʻnatuvchi boʻsh boʻlmasligi kerak", ++ "generic_server_error": "Kutilmagan server xatosi yuz berdi. Iltimos, administratoringiz bilan bogʻlaning.", ++ "global_filter_write_error": "Filtr faylini yozib boʻlmadi: %s", ++ "global_map_invalid": "Global xarita ID %s noto'g'ri", ++ "global_map_write_error": "Global xarita ID %s ni yozib boʻlmadi: %s", ++ "goto_empty": "Taxallus manzili kamida bitta haqiqiy yoʻnaltirish manzilini oʻz ichiga olishi kerak", ++ "goto_invalid": "Yoʻnaltirish manzili %s noto'g'ri", ++ "ham_learn_error": "Ham oʻrgatish xatosi: %s", ++ "iam_test_connection": "Ulanish muvaffaqiyatsiz", ++ "imagick_exception": "Xato: Tasvirni oʻqishda Imagick istisnosi", ++ "img_dimensions_exceeded": "Tasvir maksimal tasvir oʻlchamidan oshib ketdi", ++ "img_invalid": "Tasvir faylini tekshirib boʻlmadi", ++ "img_size_exceeded": "Tasvir maksimal fayl oʻlchamidan oshib ketdi", ++ "img_tmp_missing": "Tasvir faylini tekshirib boʻlmadi: Vaqtinchalik fayl topilmadi", ++ "invalid_bcc_map_type": "Noto'g'ri BCC xarita turi", ++ "invalid_destination": "Manzil formati \"%s\" noto'g'ri", ++ "invalid_filter_type": "Noto'g'ri filtr turi", ++ "invalid_host": "Noto'g'ri xost belgilangan: %s", ++ "invalid_mime_type": "Noto'g'ri MIME turi", ++ "invalid_nexthop": "Keyingi nuqta formati noto'g'ri", ++ "invalid_nexthop_authenticated": "Keyingi nuqta boshqa maʼlumotlar bilan mavjud, iltimos avval bu keyingi nuqta uchun mavjud maʼlumotlarni yangilang.", ++ "invalid_recipient_map_new": "Yangi qabul qiluvchi noto'g'ri belgilangan: %s", ++ "invalid_recipient_map_old": "Asl qabul qiluvchi noto'g'ri belgilangan: %s", ++ "invalid_reset_token": "Noto'g'ri tiklash tokeni", ++ "ip_list_empty": "Ruxsat etilgan IP roʻyxati boʻsh boʻlolmaydi", ++ "is_alias": "%s allaqachon taxallus manzili sifatida tanilgan", ++ "is_alias_or_mailbox": "%s allaqachon taxallus, pochta qutisi yoki taxallus domenidan kengaytirilgan taxallus manzili sifatida tanilgan.", ++ "is_spam_alias": "%s allaqachon vaqtinchalik taxallus manzili (spam taxallus manzili) sifatida tanilgan", ++ "last_key": "Oxirgi kalitni oʻchirib boʻlmaydi, iltimos uning oʻrniga TFA ni oʻchiring.", ++ "login_failed": "Kirish muvaffaqiyatsiz", ++ "mailbox_defquota_exceeds_mailbox_maxquota": "Standart kvota maksimal kvota chegarasidan oshib ketdi", ++ "mailbox_invalid": "Pochta qutisi nomi noto'g'ri", ++ "mailbox_quota_exceeded": "Kvota domen chegarasidan oshib ketdi (maks. %d MiB)", ++ "mailbox_quota_exceeds_domain_quota": "Maks. kvota domen kvota chegarasidan oshib ketdi", ++ "mailbox_quota_left_exceeded": "Yetarli joy qolmadi (qolgan joy: %d MiB)", ++ "mailboxes_in_use": "Maks. pochta qutilari %d dan katta yoki teng boʻlishi kerak", ++ "malformed_username": "Noto'g'ri shakldagi foydalanuvchi nomi", ++ "map_content_empty": "Xarita mazmuni boʻsh boʻlolmaydi", ++ "max_age_invalid": "Maks. yosh %s noto'g'ri", ++ "max_alias_exceeded": "Maks. taxalluslar oshib ketdi", ++ "max_mailbox_exceeded": "Maks. pochta qutilari oshib ketdi (%d / %d)", ++ "max_quota_in_use": "Pochta qutisi kvotasi %d MiB dan katta yoki teng boʻlishi kerak", ++ "maxquota_empty": "Bitta pochta qutisi uchun maks. kvota 0 boʻlmasligi kerak.", ++ "mode_invalid": "Rejim %s noto'g'ri", ++ "mx_invalid": "MX yozuvi %s noto'g'ri", ++ "mysql_error": "MySQL xatosi: %s", ++ "network_host_invalid": "Noto'g'ri tarmoq yoki xost: %s", ++ "next_hop_interferes": "%s keyingi nuqta %s bilan tortishuvga kirishadi", ++ "next_hop_interferes_any": "Mavjud keyingi nuqta %s bilan tortishuvga kirishadi", ++ "nginx_reload_failed": "Nginx qayta yuklash muvaffaqiyatsiz: %s", ++ "no_user_defined": "Foydalanuvchi belgilanmagan", ++ "object_exists": "%s obyekti allaqachon mavjud", ++ "object_is_not_numeric": "%s qiymati raqamli emas", ++ "password_complexity": "Parol siyosatga mos kelmaydi", ++ "password_empty": "Parol boʻsh boʻlmasligi kerak", ++ "password_mismatch": "Tasdiqlash paroli mos kelmadi", ++ "password_reset_invalid_user": "Pochta qutisi topilmadi yoki tiklash uchun e-pochta oʻrnatilmagan", ++ "password_reset_na": "Parolni tiklash hozirda mavjud emas. Iltimos, administratoringiz bilan bogʻlaning.", ++ "policy_list_from_exists": "Berilgan nomli yozuv mavjud", ++ "policy_list_from_invalid": "Yozuv noto'g'ri formatga ega", ++ "private_key_error": "Maxfiy kalit xatosi: %s", ++ "pushover_credentials_missing": "Pushover tokeni va/yoki kaliti yetishmayapti", ++ "pushover_key": "Pushover kaliti notoʻgʻri formatga ega", ++ "pushover_token": "Pushover tokeni notoʻgʻri formatga ega", ++ "quarantine_category_invalid": "Karantin turkumi quyidagilardan biri boʻlishi kerak: add_header, reject, all", ++ "quota_not_0_not_numeric": "Kvota raqamli va >= 0 boʻlishi kerak", ++ "recipient_map_entry_exists": "Qabul qiluvchi xaritasi yozuvi \"%s\" mavjud", ++ "recovery_email_failed": "Tiklash e-pochtasini yuborib boʻlmadi. Iltimos, administratoringiz bilan bogʻlaning.", ++ "redis_error": "Redis xatosi: %s", ++ "relayhost_invalid": "Xarita yozuvi %s noto'g'ri", ++ "release_send_failed": "Xabarni chiqarib boʻlmadi: %s", ++ "required_data_missing": "Talab qilinadigan ma'lumotlar %s yetishmayapti", ++ "reset_f2b_regex": "Regex filtrini oʻz vaqtida tiklab boʻlmadi, iltimos qaytadan urinib koʻring yoki bir necha soniya kuting va sahifani qayta yuklang.", ++ "reset_token_limit_exceeded": "Tiklash tokeni chegarasi oshib ketdi. Iltimos, keyinroq urinib koʻring.", ++ "resource_invalid": "Resurs nomi %s noto'g'ri", ++ "rl_timeframe": "Tezlik chegarasi vaqt oraligʻi noto'g'ri", ++ "rspamd_ui_pw_length": "Rspamd UI paroli kamida 6 ta belgi uzunlikda boʻlishi kerak", ++ "script_empty": "Skript boʻsh boʻlolmaydi", ++ "sender_acl_invalid": "Joʻnatuvchi ACL qiymati %s noto'g'ri", ++ "set_acl_failed": "ACL ni oʻrnatib boʻlmadi", ++ "settings_map_invalid": "Sozlamalar xaritasi ID %s noto'g'ri", ++ "sieve_error": "Sieve tahlilchisi xatosi: %s", ++ "spam_learn_error": "Spam oʻrgatish xatosi: %s", ++ "subject_empty": "Mavzu boʻsh boʻlmasligi kerak", ++ "target_domain_invalid": "Maqsad domen %s noto'g'ri", ++ "targetd_not_found": "Maqsad domen %s topilmadi", ++ "targetd_relay_domain": "Maqsad domen %s relay domen", ++ "template_exists": "%s shabloni allaqachon mavjud", ++ "template_id_invalid": "Shablon ID %s noto'g'ri", ++ "template_name_invalid": "Shablon nomi noto'g'ri", ++ "temp_error": "Vaqtinchalik xato", ++ "text_empty": "Matn boʻsh boʻlmasligi kerak", ++ "tfa_token_invalid": "TFA tokeni noto'g'ri", ++ "tls_policy_map_dest_invalid": "Siyosat manzili noto'g'ri", ++ "tls_policy_map_entry_exists": "TLS siyosati xaritasi yozuvi \"%s\" mavjud", ++ "tls_policy_map_parameter_invalid": "Siyosat parametri noto'g'ri", ++ "to_invalid": "Qabul qiluvchi boʻsh boʻlmasligi kerak", ++ "totp_verification_failed": "TOTP tekshiruvi muvaffaqiyatsiz", ++ "transport_dest_exists": "Transport manzili \"%s\" mavjud", ++ "webauthn_verification_failed": "WebAuthn tekshiruvi muvaffaqiyatsiz: %s", ++ "webauthn_authenticator_failed": "Tanlangan autentifikator topilmadi", ++ "webauthn_publickey_failed": "Tanlangan autentifikator uchun ochiq kalit saqlanmagan", ++ "webauthn_username_failed": "Tanlangan autentifikator boshqa hisobga tegishli", ++ "unknown": "Noma'lum xato yuz berdi", ++ "unknown_tfa_method": "Noma'lum TFA usuli", ++ "unlimited_quota_acl": "Cheksiz kvota ACL tomonidan taqiqlangan", ++ "username_invalid": "Foydalanuvchi nomi %s ishlatib boʻlmaydi", ++ "validity_missing": "Iltimos, amal qilish muddatini tayinlang", ++ "value_missing": "Iltimos, barcha qiymatlarni kiriting", ++ "version_invalid": "Versiya %s noto'g'ri", ++ "yotp_verification_failed": "Yubico OTP tekshiruvi muvaffaqiyatsiz: %s" ++ }, ++ "datatables": { ++ "collapse_all": "Hammasini yigʻish", ++ "decimal": ".", ++ "emptyTable": "Jadvalda ma'lumot mavjud emas", ++ "expand_all": "Hammasini kengaytirish", ++ "info": "_TOTAL_ tadan _START_ dan _END_ gacha koʻrsatilmoqda", ++ "infoEmpty": "0 tadan 0 dan 0 gacha koʻrsatilmoqda", ++ "infoFiltered": "(jami _MAX_ tadan filtrlangan)", ++ "infoPostFix": "", ++ "thousands": ",", ++ "lengthMenu": "_MENU_ ta yozuvni koʻrsatish", ++ "loadingRecords": "Yuklanmoqda...", ++ "processing": "Iltimos, kuting...", ++ "search": "Qidirish:", ++ "zeroRecords": "Mos keladigan yozuvlar topilmadi", ++ "paginate": { ++ "first": "Birinchi", ++ "last": "Oxirgi", ++ "next": "Keyingi", ++ "previous": "Oldingi" ++ }, ++ "aria": { ++ "sortAscending": ": ustunni oʻsish boʻyicha saralash uchun faollashtiring", ++ "sortDescending": ": ustunni kamayish boʻyicha saralash uchun faollashtiring" ++ } ++ }, ++ "debug": { ++ "architecture": "Arxitektura", ++ "chart_this_server": "Diagramma (bu server)", ++ "containers_info": "Konteyner ma'lumotlari", ++ "container_running": "Ishlamoqda", ++ "container_disabled": "Konteyner toʻxtatilgan yoki oʻchirilgan", ++ "container_stopped": "Toʻxtatilgan", ++ "cores": "Yadrolar", ++ "current_time": "Tizim vaqti", ++ "disk_usage": "Disk foydalanish", ++ "docs": "Hujjatlar", ++ "error_show_ip": "Ommaviy IP manzillarini aniqlab boʻlmadi", ++ "external_logs": "Tashqi jurnallar", ++ "history_all_servers": "Tarix (barcha serverlar)", ++ "in_memory_logs": "Xotiradagi jurnallar", ++ "last_modified": "Oxirgi oʻzgartirilgan", ++ "log_info": "

mailcow xotiradagi jurnallar Redis roʻyxatlarida toʻplanadi va har daqiqada hammomilik kamaytirish uchun LOG_LINES (%d) ga qisqartiriladi.\r\n
Xotiradagi jurnallar doimiy boʻlishi mumkin emas. Xotirada jurnal yurituvchi barcha ilovalar ham Docker daemoniga, demak standart jurnal yuritish drayveriga ham yozadi.\r\n
Xotiradagi jurnal turi konteynerlar bilan kichik muammolarni nosozliklarni bartaraf etish uchun ishlatilishi kerak.

\r\n

Tashqi jurnallar berilgan ilovaning API si orqali toʻplanadi.

\r\n

Statik jurnallar asosan faollik jurnallaridir, ular Dockerd ga yozilmaydi, lekin baribir doimiy boʻlishi kerak (API jurnallaridan tashqari).

", ++ "login_time": "Vaqt", ++ "logs": "Jurnallar", ++ "memory": "Xotira", ++ "online_users": "Onlayn foydalanuvchilar", ++ "restart_container": "Qayta ishga tushirish", ++ "service": "Xizmat", ++ "show_ip": "Ommaviy IP ni koʻrsatish", ++ "size": "Oʻlcham", ++ "started_at": "Boshlangan vaqt", ++ "started_on": "Boshlangan sana", ++ "static_logs": "Statik jurnallar", ++ "success": "Muvaffaqiyatli", ++ "system_containers": "Tizim va konteynerlar", ++ "timezone": "Vaqt mintaqasi", ++ "uptime": "Ishlash vaqti", ++ "update_available": "Yangilanish mavjud", ++ "no_update_available": "Tizim oxirgi versiyada", ++ "update_failed": "Yangilanishni tekshirib boʻlmadi", ++ "username": "Foydalanuvchi nomi", ++ "wip": "Hozir ishlab chiqilmoqda" ++ }, ++ "diagnostics": { ++ "cname_from_a": "Qiymat A/AAAA yozuvidan olingan. Yozuv toʻgʻri resursga ishora qilsa, bu qoʻllab-quvvatlanadi.", ++ "dns_records": "DNS yozuvlari", ++ "dns_records_24hours": "DNS ga kiritilgan oʻzgarishlar ushbu sahifada toʻgʻri aks ettirilishi uchun 24 soatgacha vaqt ketishi mumkinligini hisobga oling. Bu DNS yozuvlaringizni qanday sozlash kerakligini osongina koʻrish va barcha yozuvlaringiz DNS da toʻgʻri saqlanganligini tekshirish uchun moʻljallangan.", ++ "dns_records_data": "Toʻgʻri ma'lumot", ++ "dns_records_docs": "Iltimos, hujjatlarga ham murojaat qiling.", ++ "dns_records_name": "Nomi", ++ "dns_records_status": "Joriy holat", ++ "dns_records_type": "Tur", ++ "optional": "Bu yozuv ixtiyoriy." ++ }, ++ "edit": { ++ "acl": "ACL (Ruxsat)", ++ "active": "Faol", ++ "admin": "Administratorni tahrirlash", ++ "advanced_settings": "Kengaytirilgan sozlamalar", ++ "alias": "Taxallusni tahrirlash", ++ "allow_from_smtp": "Faqat ushbu IP larga SMTP dan foydalanishga ruxsat berish", ++ "allow_from_smtp_info": "Barcha joʻnatuvchilarga ruxsat berish uchun boʻsh qoldiring.
IPv4/IPv6 manzillari va tarmoqlari.", ++ "allowed_protocols": "Toʻgʻridan-toʻgʻri foydalanuvchi kirishi uchun ruxsat etilgan protokollar (ilova paroli protokollariga taʼsir qilmaydi)", ++ "app_name": "Ilova nomi", ++ "app_passwd": "Ilova paroli", ++ "app_passwd_protocols": "Ilova paroli uchun ruxsat etilgan protokollar", ++ "automap": "Papkalarni avtomatik xaritalashga harakat qilish (\"Sent items\", \"Sent\" => \"Sent\" va h.k.)", ++ "backup_mx_options": "Relay sozlamalari", ++ "bcc_dest_format": "BCC manzili bitta haqiqiy e-pochta manzili boʻlishi kerak.
Agar bir nechta manzilga nusxa joʻnatish kerak boʻlsa, taxallus yarating va shu yerda ishlating.", ++ "client_id": "Mijoz ID", ++ "client_secret": "Mijoz maxfiy soʻzi", ++ "comment_info": "Maxfiy izoh foydalanuvchiga koʻrinmaydi, ommaviy izoh esa foydalanuvchi koʻrinishida ustiga sichqoncha kelganda maslahat sifatida koʻrsatiladi", ++ "created_on": "Yaratilgan sana", ++ "custom_attributes": "Maxsus atributlar", ++ "delete1": "Tugatilgach manbadan oʻchirish", ++ "delete2": "Manbada boʻlmagan xabarlarni manzildan oʻchirish", ++ "delete2duplicates": "Manzildagi dublikatlarni oʻchirish", ++ "delete_ays": "Iltimos, oʻchirish jarayonini tasdiqlang.", ++ "description": "Tavsif", ++ "disable_login": "Kirishni taqiqlash (kiruvchi pochta hali ham qabul qilinadi)", ++ "domain": "Domenni tahrirlash", ++ "domain_admin": "Domen administratorini tahrirlash", ++ "domain_footer": "Domen boʻyicha pastki qism", ++ "domain_footer_html": "HTML pastki qism", ++ "domain_footer_info": "Domen boʻyicha pastki qismlar ushbu domendagi manzilga bog'liq barcha chiquvchi xatlarga qoʻshiladi.
Pastki qism uchun quyidagi oʻzgaruvchilarni ishlatish mumkin:", ++ "domain_footer_info_vars": { ++ "auth_user": "{= auth_user =} - MTA tomonidan belgilangan autentifikatsiya qilingan foydalanuvchi nomi", ++ "from_user": "{= from_user =} - Konvertning Kimdan qismi, masalan \"moo@mailcow.tld\" uchun \"moo\" qaytaradi", ++ "from_name": "{= from_name =} - Konvertning Kimdan ismi, masalan \"Mailcow <moo@mailcow.tld>\" uchun \"Mailcow\" qaytaradi", ++ "from_addr": "{= from_addr =} - Konvertning Kimdan manzili qismi", ++ "from_domain": "{= from_domain =} - Konvertning Kimdan domeni qismi", ++ "custom": "{= foo =} - Agar pochta qutisida \"bar\" qiymatli \"foo\" maxsus atributi boʻlsa \"bar\" qaytaradi" ++ }, ++ "domain_footer_plain": "PLAIN pastki qism", ++ "domain_footer_skip_replies": "Javob xatlarida pastki qismni e'tiborsiz qoldirish", ++ "domain_quota": "Domen kvotasi", ++ "domains": "Domenlar", ++ "dont_check_sender_acl": "%s domeni uchun joʻnatuvchi tekshiruvini oʻchirish (+ taxallus domenlari)", ++ "edit_alias_domain": "Taxallus domenini tahrirlash", ++ "encryption": "Shifrlash", ++ "exclude": "Obyektlarni istisno qilish (regex)", ++ "extended_sender_acl": "Tashqi joʻnatuvchi manzillari", ++ "extended_sender_acl_info": "DKIM domen kaliti mavjud boʻlsa, import qilinishi kerak.
\r\n Ushbu serverni mos SPF TXT yozuviga qoʻshishni unutmang.
\r\n Ushbu serverga tashqi manzil bilan ust-ust tushadigan domen yoki taxallus domeni qoʻshilganda, tashqi manzil olib tashlanadi.
\r\n *@domain.tld sifatida joʻnatishga ruxsat berish uchun @domain.tld dan foydalaning.", ++ "force_pw_update": "Keyingi kirishda parolni majburiy yangilash", ++ "force_pw_update_info": "Bu foydalanuvchi faqat %s ga kira oladi. Ilova parollari ishlash holatida qoladi.", ++ "footer_exclude": "Pastki qismdan istisno qilish", ++ "full_name": "Toʻliq ism", ++ "gal": "Global manzillar roʻyxati", ++ "gal_info": "GAL domenning barcha obyektlarini oʻz ichiga oladi va hech bir foydalanuvchi tomonidan tahrirlanmaydi. Oʻchirilsa, SOGodagi bandlik maʼlumotlari yoʻqoladi! Oʻzgarishlarni qoʻllash uchun SOGoni qayta ishga tushiring.", ++ "generate": "yaratish", ++ "grant_types": "Grant turlari", ++ "hostname": "Xost nomi", ++ "inactive": "Nofaol", ++ "internal": "Ichki", ++ "internal_info": "Ichki taxalluslarga faqat oʻz domeni yoki taxallus domenlaridan kirish mumkin.", ++ "sender_allowed": "Ushbu taxallus orqali joʻnatishga ruxsat berish", ++ "sender_allowed_info": "Oʻchirilgan boʻlsa, bu taxallus faqat xat qabul qilishi mumkin. Maxsus pochta qutilariga joʻnatishga ruxsat berish uchun joʻnatuvchi ACL dan foydalaning.", ++ "kind": "Turi", ++ "last_modified": "Oxirgi oʻzgartirilgan", ++ "lookup_mx": "Manzil — MX nomiga mos keladigan muntazam ifoda (.*\\.google\\.com — google.com bilan tugaydigan MX ga yoʻnaltirilgan barcha pochtani ushbu nuqta orqali yoʻnaltirish uchun)", ++ "mailbox": "Pochta qutisini tahrirlash", ++ "mailbox_quota_def": "Standart pochta qutisi kvotasi", ++ "mailbox_relayhost_info": "Faqat pochta qutisi va to'g'ridan-to'g'ri taxalluslarga qoʻllaniladi, domen relay xostini bekor qiladi.", ++ "mailbox_rename": "Pochta qutisini qayta nomlash", ++ "mailbox_rename_agree": "Men zaxira nusxasini yaratdim.", ++ "mailbox_rename_warning": "MUHIM! Pochta qutisini qayta nomlashdan oldin zaxira nusxasi yarating.", ++ "mailbox_rename_alias": "Taxallusni avtomatik yaratish", ++ "mailbox_rename_title": "Yangi mahalliy pochta qutisi nomi", ++ "max_aliases": "Maks. taxalluslar", ++ "max_mailboxes": "Mumkin boʻlgan maks. pochta qutilari", ++ "max_quota": "Bitta pochta qutisining maks. kvotasi (MiB)", ++ "maxage": "Masofadan soʻraladigan xabarlarning maksimal yoshi (kunlarda)
(0 = yoshni e'tiborsiz qoldirish)", ++ "maxbytespersecond": "Maks. soniyaga bayt
(0 = cheksiz)", ++ "mbox_rl_info": "Bu tezlik chegarasi SASL kirish nomiga qoʻllaniladi, u kirgan foydalanuvchi tomonidan ishlatiladigan har qanday \"from\" manziliga mos keladi. Pochta qutisi tezlik chegarasi domen boʻyicha tezlik chegarasini bekor qiladi.", ++ "mins_interval": "Oraliq (daqiqa)", ++ "mta_sts": "MTA-STS", ++ "mta_sts_info": "MTA-STS — pochta serverlari oʻrtasida xat yetkazib berishni haqiqiy sertifikatli TLS dan foydalanishga majburlovchi standart.
U DNSSEC mavjud emasligi yoki qoʻllab-quvvatlanmasligi sababli DANE imkoni boʻlmaganda ishlatiladi.
Eslatma: Agar qabul qiluvchi domen DNSSEC bilan DANE ni qoʻllab-quvvatlasa, DANE har doim afzal koʻriladi — MTA-STS faqat zaxira sifatida ishlaydi.", ++ "mta_sts_version": "Versiya", ++ "mta_sts_version_info": "MTA-STS standartining versiyasini belgilaydi — hozirda faqat STSv1 haqiqiy.", ++ "mta_sts_mode": "Rejim", ++ "mta_sts_mode_info": "Tanlash uchun uchta rejim mavjud:
  • testing — siyosat faqat kuzatiladi, buzilishlar taʼsir koʻrsatmaydi.
  • enforce — siyosat qatʼiy qoʻllaniladi, haqiqiy TLS siz ulanishlar rad etiladi.
  • none — siyosat eʼlon qilinadi, ammo qoʻllanilmaydi.
", ++ "mta_sts_max_age": "Maks. yosh", ++ "mta_sts_max_age_info": "Qabul qiluvchi pochta serverlari ushbu siyosatni qayta olishdan oldin keshlashi mumkin boʻlgan vaqt (soniyalarda).", ++ "mta_sts_mx": "MX server", ++ "mta_sts_mx_info": "Faqat aniq sanab oʻtilgan pochta server xost nomlariga joʻnatishga ruxsat beradi; joʻnatuvchi MTA DNS MX xost nomi siyosat roʻyxatiga mos kelishini tekshiradi va faqat haqiqiy TLS sertifikati bilan yetkazib berishga ruxsat beradi (MITM ga qarshi himoya qiladi).", ++ "mta_sts_mx_notice": "Bir nechta MX serverlar belgilanishi mumkin (vergul bilan ajratilgan).", ++ "multiple_bookings": "Bir nechta bandlovlar", ++ "none_inherit": "Hech biri / Meros qilib olish", ++ "nexthop": "Keyingi nuqta", ++ "password": "Parol", ++ "password_recovery_email": "Parolni tiklash e-pochtasi", ++ "password_repeat": "Tasdiqlash paroli (takrorlang)", ++ "previous": "Oldingi sahifa", ++ "private_comment": "Maxfiy izoh", ++ "public_comment": "Ommaviy izoh", ++ "pushover": "Pushover", ++ "pushover_evaluate_x_prio": "Yuqori muhimlikdagi xatni eskalatsiya qilish [X-Priority: 1]", ++ "pushover_info": "Push bildirishnoma sozlamalari %s ga taxalluslar bilan birga (umumiy, umumiy boʻlmagan, teglangan) yetkazib beriladigan barcha toza (spam boʻlmagan) xatlarga qoʻllaniladi.", ++ "pushover_only_x_prio": "Faqat yuqori muhimlikdagi xatlarni koʻrib chiqish [X-Priority: 1]", ++ "pushover_sender_array": "Faqat quyidagi joʻnatuvchi e-pochta manzillarini koʻrib chiqish (vergul bilan ajratilgan)", ++ "pushover_sender_regex": "Quyidagi joʻnatuvchi regexini koʻrib chiqish", ++ "pushover_text": "Bildirishnoma matni", ++ "pushover_title": "Bildirishnoma sarlavhasi", ++ "pushover_sound": "Tovush", ++ "pushover_vars": "Joʻnatuvchi filtri belgilanmagan boʻlsa, barcha xatlar koʻrib chiqiladi.
Regex filtrlari va aniq joʻnatuvchi tekshiruvlari alohida belgilanishi mumkin va ketma-ket koʻrib chiqiladi. Ular bir-biriga bogʻliq emas.
Matn va sarlavha uchun ishlatiladigan oʻzgaruvchilar (ma'lumotlarni himoya qilish siyosatiga e'tibor bering)", ++ "pushover_verify": "Maʼlumotlarni tekshirish", ++ "quota_mb": "Kvota (MiB)", ++ "quota_warning_bcc": "Kvota ogohlantirishi BCC", ++ "quota_warning_bcc_info": "Ogohlantirishlar alohida nusxa sifatida quyidagi qabul qiluvchilarga yuboriladi. Mavzu mos foydalanuvchi nomi bilan qavs ichida qoʻshib qoʻyiladi, masalan: Kvota ogohlantirishi (user@example.com).", ++ "ratelimit": "Tezlik chegarasi", ++ "redirect_uri": "Yoʻnaltirish/Qaytarish URL", ++ "relay_all": "Barcha qabul qiluvchilarni relay qilish", ++ "relay_all_info": "↪ Agar barcha qabul qiluvchilarni relay qilmaslikni tanlasangiz, relay qilinishi kerak boʻlgan har bir qabul qiluvchi uchun (\"koʻr\") pochta qutisi qoʻshishingiz kerak boʻladi.", ++ "relay_domain": "Ushbu domenni relay qilish", ++ "relay_transport_info": "
Maʼlumot
Bu domen uchun maxsus manzilga transport xaritalarini belgilashingiz mumkin. Agar oʻrnatilmagan boʻlsa, MX qidiruvi amalga oshiriladi.", ++ "relay_unknown_only": "Faqat mavjud boʻlmagan pochta qutilarini relay qilish. Mavjud pochta qutilari mahalliy yetkazib beriladi.", ++ "relayhost": "Joʻnatuvchiga bogʻliq transportlar", ++ "remove": "Olib tashlash", ++ "resource": "Resurs", ++ "save": "Oʻzgarishlarni saqlash", ++ "scope": "Qamrov", ++ "sender_acl": "Quyidagi sifatida joʻnatishga ruxsat berish", ++ "sender_acl_disabled": "Joʻnatuvchi tekshiruvi oʻchirilgan", ++ "sender_acl_info": "Agar A pochta qutisi foydalanuvchisi B pochta qutisi foydalanuvchisi sifatida joʻnatishga ruxsat etilgan boʻlsa, joʻnatuvchi manzili SOGo da tanlanadigan \"from\" maydoni sifatida avtomatik koʻrsatilmaydi.
\r\n B pochta qutisi foydalanuvchisi A pochta qutisi foydalanuvchisi oʻz manzilini joʻnatuvchi sifatida tanlay olishi uchun SOGo da delegatsiya yaratishi kerak. SOGo da pochta qutisini delegatsiya qilish uchun pochta koʻrinishida yuqori chap qismdagi pochta qutisi nomingiz oʻng tomonidagi menyudan (uch nuqta) foydalaning. Bu xatti-harakat taxallus manzillariga qoʻllanmaydi.", ++ "sieve_desc": "Qisqa tavsif", ++ "sieve_type": "Filtr turi", ++ "skipcrossduplicates": "Papkalararo dublikat xabarlarni oʻtkazib yuborish (birinchi kelgan, birinchi xizmatlanadi)", ++ "sogo_access": "SOGo ga toʻgʻridan-toʻgʻri yoʻnaltirish", ++ "sogo_access_info": "Tizimga kirgandan keyin foydalanuvchi avtomatik ravishda SOGo ga yoʻnaltiriladi.", ++ "sogo_visible": "Taxallus SOGo da koʻrinadi", ++ "sogo_visible_info": "Bu variant faqat SOGo da koʻrsatilishi mumkin boʻlgan obyektlarga taʼsir qiladi (kamida bitta mahalliy pochta qutisiga ishora qiluvchi umumiy yoki umumiy boʻlmagan taxallus manzillari). Yashirilgan boʻlsa, taxallus SOGo da tanlanadigan joʻnatuvchi sifatida koʻrinmaydi.", ++ "spam_alias": "Vaqt cheklangan taxallus manzillarini yaratish yoki oʻzgartirish", ++ "spam_filter": "Spam filtri", ++ "spam_policy": "Elementlarni ruxsat etilgan/qora roʻyxatga qoʻshish yoki olib tashlash", ++ "spam_score": "Maxsus spam bahosini oʻrnatish", ++ "subfolder2": "Manzilning subpapkasiga sinxronizatsiya qilish
(boʻsh = subpapkadan foydalanmang)", ++ "syncjob": "Sinxronizatsiya vazifasini tahrirlash", ++ "target_address": "Yoʻnaltirish manzil(lar)i (vergul bilan ajratilgan)", ++ "target_domain": "Maqsad domen", ++ "timeout1": "Masofaviy xostga ulanish vaqtining tugashi", ++ "timeout2": "Mahalliy xostga ulanish vaqtining tugashi", ++ "title": "Obyektni tahrirlash", ++ "unchanged_if_empty": "Oʻzgartirilmagan boʻlsa, boʻsh qoldiring", ++ "username": "Foydalanuvchi nomi", ++ "validate_save": "Tekshirish va saqlash" ++ }, ++ "fido2": { ++ "confirm": "Tasdiqlash", ++ "fido2_auth": "FIDO2 bilan kirish", ++ "fido2_success": "Qurilma muvaffaqiyatli roʻyxatdan oʻtkazildi", ++ "fido2_validation_failed": "Tekshirish muvaffaqiyatsiz", ++ "fn": "Doʻstona nom", ++ "known_ids": "Maʼlum ID lar", ++ "none": "Oʻchirilgan", ++ "register_status": "Roʻyxatga olish holati", ++ "rename": "Qayta nomlash", ++ "set_fido2": "FIDO2 qurilmasini roʻyxatdan oʻtkazish", ++ "set_fido2_touchid": "Apple M1 da Touch ID ni roʻyxatdan oʻtkazish", ++ "set_fn": "Doʻstona nomni oʻrnatish", ++ "start_fido2_validation": "FIDO2 tekshiruvini boshlash" ++ }, ++ "footer": { ++ "cancel": "Bekor qilish", ++ "confirm_delete": "Oʻchirishni tasdiqlash", ++ "delete_now": "Hozir oʻchirish", ++ "delete_these_items": "Iltimos, quyidagi obyekt ID siga oʻzgarishlaringizni tasdiqlang", ++ "hibp_check": "haveibeenpwned.com ga qarshi tekshirish", ++ "hibp_nok": "Mos keldi! Bu xavfli parol boʻlishi mumkin!", ++ "hibp_ok": "Mos kelmadi.", ++ "loading": "Iltimos, kuting...", ++ "nothing_selected": "Hech narsa tanlanmadi", ++ "restart_container": "Konteynerni qayta ishga tushirish", ++ "restart_container_info": "Muhim: Yumshoq qayta ishga tushirish biroz vaqt olishi mumkin, iltimos uning tugashini kuting.", ++ "restart_now": "Hozir qayta ishga tushirish", ++ "restarting_container": "Konteyner qayta ishga tushirilmoqda, bu biroz vaqt olishi mumkin" ++ }, ++ "header": { ++ "administration": "Konfiguratsiya va tafsilotlar", ++ "apps": "Ilovalar", ++ "debug": "Maʼlumot", ++ "email": "E-pochta", ++ "mailcow_system": "Tizim", ++ "mailcow_config": "Konfiguratsiya", ++ "quarantine": "Karantin", ++ "restart_netfilter": "Netfilterni qayta ishga tushirish", ++ "restart_sogo": "SOGoni qayta ishga tushirish", ++ "user_settings": "Foydalanuvchi sozlamalari" ++ }, ++ "info": { ++ "awaiting_tfa_confirmation": "TFA tasdiqlanishi kutilmoqda", ++ "no_action": "Amal qoʻllanib boʻlmaydi", ++ "session_expires": "Sessiyangiz taxminan 15 soniyadan keyin tugaydi" ++ }, ++ "login": { ++ "back_to_mailcow": "mailcow ga qaytish", ++ "delayed": "Kirish %s soniyaga kechiktirildi.", ++ "fido2_webauthn": "FIDO2/WebAuthn kirish", ++ "forgot_password": "> Parolni unutdingizmi?", ++ "invalid_pass_reset_token": "Parolni tiklash tokeni noto'g'ri yoki muddati tugagan.
Iltimos, yangi parolni tiklash havolasini soʻrang.", ++ "login": "Kirish", ++ "login_linkstext": "Toʻgʻri kirish emasmi?", ++ "login_usertext": "Foydalanuvchi sifatida kirish", ++ "login_domainadmintext": "Domen administratori sifatida kirish", ++ "login_admintext": "Administrator sifatida kirish", ++ "login_user": "Foydalanuvchi kirishi", ++ "login_dadmin": "Domen-administratori kirishi", ++ "login_admin": "Administrator kirishi", ++ "mobileconfig_info": "Soʻralgan Apple ulanish profilini yuklab olish uchun pochta qutisi foydalanuvchisi sifatida kiring.", ++ "new_password": "Yangi parol", ++ "new_password_confirm": "Yangi parolni tasdiqlang", ++ "other_logins": "yoki quyidagi orqali kiring", ++ "password": "Parol", ++ "reset_password": "Parolni tiklash", ++ "request_reset_password": "Parol oʻzgartirishni soʻrash", ++ "username": "Foydalanuvchi nomi", ++ "email": "E-pochta manzili" ++ }, ++ "mailbox": { ++ "action": "Amal", ++ "activate": "Faollashtirish", ++ "active": "Faol", ++ "add": "Qoʻshish", ++ "add_alias": "Taxallus qoʻshish", ++ "add_alias_expand": "Taxallusni taxallus domenlari boʻylab kengaytirish", ++ "add_bcc_entry": "BCC xaritasi qoʻshish", ++ "add_domain": "Domen qoʻshish", ++ "add_domain_alias": "Domen taxallusini qoʻshish", ++ "add_domain_record_first": "Iltimos, avval domen qoʻshing", ++ "add_filter": "Filtr qoʻshish", ++ "add_mailbox": "Pochta qutisi qoʻshish", ++ "add_recipient_map_entry": "Qabul qiluvchi xaritasini qoʻshish", ++ "add_resource": "Resurs qoʻshish", ++ "add_template": "Shablon qoʻshish", ++ "add_tls_policy_map": "TLS siyosati xaritasini qoʻshish", ++ "address_rewriting": "Manzilni qayta yozish", ++ "alias": "Taxallus", ++ "alias_domain_alias_hint": "Taxalluslar domen taxalluslariga avtomatik qoʻllanilmaydi. my-alias@domain taxallus manzili my-alias@alias-domain manzilini qoplamaydi (bu yerda \"alias-domain\" — \"domain\" uchun tasavvur qilingan taxallus domeni).
Tashqi pochta qutisiga xatni yoʻnaltirish uchun sieve filtridan foydalaning (\"Filtrlar\" yorligʻiga qarang yoki SOGo -> Forwarder dan foydalaning). Yoʻq taxalluslarni avtomatik qoʻshish uchun \"Taxallusni taxallus domenlari boʻylab kengaytirish\" dan foydalaning.", ++ "alias_domain_backupmx": "Relay domeni uchun taxallus domeni nofaol", ++ "aliases": "Taxalluslar", ++ "all_domains": "Barcha domenlar", ++ "allow_from_smtp": "Faqat ushbu IP larga SMTP dan foydalanishga ruxsat berish", ++ "allow_from_smtp_info": "Barcha joʻnatuvchilarga ruxsat berish uchun boʻsh qoldiring.
IPv4/IPv6 manzillari va tarmoqlari.", ++ "allowed_protocols": "Ruxsat etilgan protokollar", ++ "backup_mx": "Relay domeni", ++ "bcc": "BCC", ++ "bcc_destination": "BCC manzili", ++ "bcc_destinations": "BCC manzili", ++ "bcc_info": "BCC xaritalari barcha xabarlarning nusxalarini boshqa manzilga jimgina yoʻnaltirish uchun ishlatiladi. Qabul qiluvchi xaritasi turi yozuvi mahalliy manzil xatning qabul qiluvchisi sifatida ishlaganda ishlatiladi. Joʻnatuvchi xaritalari ham xuddi shu tamoyilga muvofiq ishlaydi.
\r\n Mahalliy manzilga yetkazib berish muvaffaqiyatsiz boʻlsa, xabar berilmaydi.", ++ "bcc_local_dest": "Mahalliy manzil", ++ "bcc_map": "BCC xaritasi", ++ "bcc_map_type": "BCC turi", ++ "bcc_maps": "BCC xaritalari", ++ "bcc_rcpt_map": "Qabul qiluvchi xaritasi", ++ "bcc_sender_map": "Joʻnatuvchi xaritasi", ++ "bcc_to_rcpt": "Qabul qiluvchi xaritasi turiga oʻtish", ++ "bcc_to_sender": "Joʻnatuvchi xaritasi turiga oʻtish", ++ "bcc_type": "BCC turi", ++ "booking_null": "Doimo boʻsh sifatida koʻrsatish", ++ "booking_0_short": "Doimo boʻsh", ++ "booking_custom": "Maxsus bandlovlar soni bilan qatʼiy cheklash", ++ "booking_custom_short": "Qatʼiy chegara", ++ "booking_ltnull": "Cheksiz, lekin bandlangan boʻlsa band sifatida koʻrsatish", ++ "booking_lt0_short": "Yumshoq chegara", ++ "catch_all": "Hammasini-qabul qilish", ++ "created_on": "Yaratilgan sana", ++ "daily": "Kunlik", ++ "deactivate": "Oʻchirish", ++ "description": "Tavsif", ++ "disable_login": "Kirishni taqiqlash (kiruvchi pochta hali ham qabul qilinadi)", ++ "disable_x": "Oʻchirish", ++ "dkim_domains_selector": "Tanlovchi", ++ "dkim_key_length": "DKIM kalit uzunligi (bit)", ++ "domain": "Domen", ++ "domain_admins": "Domen administratorlari", ++ "domain_aliases": "Domen taxalluslari", ++ "domain_templates": "Domen shablonlari", ++ "domain_quota": "Kvota", ++ "domain_quota_total": "Umumiy domen kvotasi", ++ "domains": "Domenlar", ++ "edit": "Tahrirlash", ++ "empty": "Natijalar yoʻq", ++ "enable_x": "Yoqish", ++ "excludes": "Istisnolar", ++ "filter_table": "Filtr jadvali", ++ "filters": "Filtrlar", ++ "fname": "Toʻliq ism", ++ "force_pw_update": "Keyingi kirishda parolni majburiy yangilash", ++ "gal": "Global manzillar roʻyxati", ++ "goto_ham": "ham sifatida oʻrgatish", ++ "goto_spam": "spam sifatida oʻrgatish", ++ "hourly": "Soatlik", ++ "iam": "Identifikatsiya provayderi", ++ "in_use": "Foydalanilmoqda (%)", ++ "inactive": "Nofaol", ++ "insert_preset": "Misol presetini kiritish \"%s\"", ++ "internal": "Ichki", ++ "kind": "Turi", ++ "last_mail_login": "Oxirgi pochta kirishi", ++ "last_modified": "Oxirgi oʻzgartirilgan", ++ "last_pw_change": "Oxirgi parol oʻzgarishi", ++ "last_run": "Oxirgi ishga tushirilgan", ++ "last_run_reset": "Keyingisini rejalashtirish", ++ "mailbox": "Pochta qutisi", ++ "mailbox_defaults": "Standart sozlamalar", ++ "mailbox_defaults_info": "Yangi pochta qutilari uchun standart sozlamalarni belgilang.", ++ "mailbox_defquota": "Standart pochta qutisi oʻlchami", ++ "mailbox_templates": "Pochta qutisi shablonlari", ++ "mailbox_quota": "Pochta qutisining maks. oʻlchami", ++ "mailboxes": "Pochta qutilari", ++ "max_aliases": "Maks. taxalluslar", ++ "max_mailboxes": "Mumkin boʻlgan maks. pochta qutilari", ++ "max_quota": "Bitta pochta qutisining maks. kvotasi", ++ "mins_interval": "Oraliq (daqiqa)", ++ "msg_num": "Xabar #", ++ "multiple_bookings": "Bir nechta bandlovlar", ++ "never": "Hech qachon", ++ "no": "✕", ++ "no_record": "%s obyekti uchun yozuv yoʻq", ++ "no_record_single": "Yozuv yoʻq", ++ "open_logs": "Jurnallarni ochish", ++ "owner": "Egasi", ++ "private_comment": "Maxfiy izoh", ++ "public_comment": "Ommaviy izoh", ++ "q_add_header": "Junk papkasiga koʻchirilganda", ++ "q_all": " Junk papkasiga koʻchirilganda va rad etilganda", ++ "q_reject": "rad etilganda", ++ "quarantine_category": "Karantin bildirishnoma turkumi", ++ "quarantine_notification": "Karantin bildirishnomalari", ++ "quick_actions": "Amallar", ++ "recipient": "Qabul qiluvchi", ++ "recipient_map": "Qabul qiluvchi xaritasi", ++ "recipient_map_info": "Qabul qiluvchi xaritalari xabar yetkazib berilishidan oldin manzilni almashtirish uchun ishlatiladi.", ++ "recipient_map_new": "Yangi qabul qiluvchi", ++ "recipient_map_new_info": "Qabul qiluvchi xaritasi manzili haqiqiy e-pochta manzili yoki domen nomi boʻlishi kerak.", ++ "recipient_map_old": "Asl qabul qiluvchi", ++ "recipient_map_old_info": "Qabul qiluvchi xaritasining asl manzili haqiqiy e-pochta manzili yoki domen nomi boʻlishi kerak.", ++ "recipient_maps": "Qabul qiluvchi xaritalari", ++ "relay_all": "Barcha qabul qiluvchilarni relay qilish", ++ "relay_unknown": "Nomaʼlum pochta qutilarini relay qilish", ++ "remove": "Olib tashlash", ++ "resources": "Resurslar", ++ "running": "Ishlamoqda", ++ "sender": "Joʻnatuvchi", ++ "set_postfilter": "Postfiltr sifatida belgilash", ++ "set_prefilter": "Prefiltr sifatida belgilash", ++ "sieve_info": "Bitta foydalanuvchi uchun bir nechta filtrlarni saqlash mumkin, lekin bir vaqtning oʻzida faqat bitta prefiltr va bitta postfiltr faol boʻlishi mumkin.
\r\nHar bir filtr tasvirlangan tartibda qayta ishlanadi. Muvaffaqiyatsiz skript ham, chiqarilgan \"keep;\" ham keyingi skriptlarning qayta ishlanishini toʻxtatmaydi. Global sieve skriptlariga oʻzgartirishlar Dovecot ni qayta ishga tushirishni keltirib chiqaradi.

Global sieve prefilter • Prefilter • Foydalanuvchi skriptlari • Postfilter • Global sieve postfilter", ++ "sieve_preset_1": "Xavfli boʻlishi mumkin boʻlgan fayl turlari bilan xatlarni rad etish", ++ "sieve_preset_2": "Aniq joʻnatuvchining xatini har doim oʻqilgan deb belgilash", ++ "sieve_preset_3": "Jimgina rad etish, keyingi sieve qayta ishlashini toʻxtatish", ++ "sieve_preset_4": "INBOX ga joylash, sieve filtrlari tomonidan keyingi qayta ishlashni oʻtkazib yuborish", ++ "sieve_preset_5": "Avto-javob (taʼtil)", ++ "sieve_preset_6": "Javob bilan xatni rad etish", ++ "sieve_preset_7": "Yoʻnaltirish va saqlash/tashlash", ++ "sieve_preset_8": "Aniq joʻnatuvchining xatini yoʻnaltirish, oʻqilgan deb belgilash va subpapkaga saralash", ++ "sieve_preset_header": "Iltimos, quyidagi misol presetlariga qarang. Batafsil maʼlumot uchun Wikipediaga qarang.", ++ "sogo_visible": "Taxallus SOGo da koʻrinadi", ++ "sogo_visible_n": "Taxallusni SOGo da yashirish", ++ "sogo_visible_y": "Taxallusni SOGo da koʻrsatish", ++ "spam_aliases": "Vaqt. taxallus", ++ "stats": "Statistika", ++ "status": "Holat", ++ "sync_jobs": "Sinxronizatsiya vazifalari", ++ "syncjob_check_log": "Jurnalni tekshirish", ++ "syncjob_last_run_result": "Oxirgi ishga tushirilgan natija", ++ "syncjob_EX_OK": "Muvaffaqiyatli", ++ "syncjob_EXIT_CONNECTION_FAILURE": "Ulanish muammosi", ++ "syncjob_EXIT_TLS_FAILURE": "Shifrlangan ulanish bilan muammo", ++ "syncjob_EXIT_AUTHENTICATION_FAILURE": "Autentifikatsiya muammosi", ++ "syncjob_EXIT_OVERQUOTA": "Maqsad pochta qutisi kvotadan oshib ketdi", ++ "syncjob_EXIT_CONNECTION_FAILURE_HOST1": "Masofaviy serverga ulanib boʻlmadi", ++ "syncjob_EXIT_AUTHENTICATION_FAILURE_USER1": "Notoʻgʻri foydalanuvchi nomi yoki parol", ++ "table_size": "Jadval oʻlchami", ++ "table_size_show_n": "%s ta element koʻrsatish", ++ "target_address": "Yoʻnaltirish manzili", ++ "target_domain": "Maqsad domen", ++ "templates": "Shablonlar", ++ "template": "Shablon", ++ "tls_enforce_in": "Kiruvchi TLS ni majburlash", ++ "tls_enforce_out": "Chiquvchi TLS ni majburlash", ++ "tls_map_dest": "Manzil", ++ "tls_map_dest_info": "Misollar: example.org, .example.org, [mail.example.org]:25", ++ "tls_map_parameters": "Parametrlar", ++ "tls_map_parameters_info": "Boʻsh yoki parametrlar, masalan: protocols=!SSLv2 ciphers=medium exclude=3DES", ++ "tls_map_policy": "Siyosat", ++ "tls_policy_maps": "TLS siyosati xaritalari", ++ "tls_policy_maps_enforced_tls": "Bu siyosatlar chiquvchi TLS ulanishlarini majburlovchi pochta qutisi foydalanuvchilari uchun ham xatti-harakatni bekor qiladi. Agar quyida siyosat boʻlmasa, bu foydalanuvchilar smtp_tls_mandatory_protocols va smtp_tls_mandatory_ciphers sifatida belgilangan standart qiymatlarni qoʻllaydi.", ++ "tls_policy_maps_info": "Bu siyosat xaritasi foydalanuvchining TLS siyosati sozlamalaridan mustaqil ravishda chiquvchi TLS transport qoidalarini bekor qiladi.
\r\n Batafsil maʼlumot uchun \"smtp_tls_policy_maps\" hujjatlarini tekshiring.", ++ "tls_policy_maps_long": "Chiquvchi TLS siyosati xaritasi bekor qilishlari", ++ "toggle_all": "Hammasini almashtirish", ++ "username": "Foydalanuvchi nomi", ++ "waiting": "Kutilmoqda", ++ "weekly": "Haftalik", ++ "yes": "✓" ++ }, ++ "oauth2": { ++ "access_denied": "OAuth2 orqali kirishga ruxsat berish uchun pochta qutisi egasi sifatida kiring.", ++ "authorize_app": "Ilovaga ruxsat berish", ++ "deny": "Rad etish", ++ "permit": "Ilovaga ruxsat berish", ++ "profile": "Profil", ++ "profile_desc": "Shaxsiy maʼlumotlarni koʻrish: foydalanuvchi nomi, toʻliq ism, yaratilgan, oʻzgartirilgan, faol", ++ "scope_ask_permission": "Ilova quyidagi ruxsatlarni soʻradi" ++ }, ++ "quarantine": { ++ "action": "Amal", ++ "atts": "Ilovalar", ++ "check_hash": "VT da fayl hashini qidirish", ++ "confirm": "Tasdiqlash", ++ "confirm_delete": "Ushbu elementni oʻchirishni tasdiqlang.", ++ "danger": "Xavf", ++ "deliver_inbox": "Inbox ga yetkazib berish", ++ "disabled_by_config": "Joriy tizim konfiguratsiyasi karantin funksiyasini oʻchirib qoʻyadi. Iltimos, karantin elementlari uchun \"pochta qutisi boʻyicha saqlash\" va \"maksimal oʻlcham\"ni oʻrnating.", ++ "download_eml": "Yuklab olish (.eml)", ++ "empty": "Natijalar yoʻq", ++ "high_danger": "Yuqori", ++ "info": "Maʼlumot", ++ "junk_folder": "Junk papkasi", ++ "learn_spam_delete": "Spam sifatida oʻrgatish va oʻchirish", ++ "low_danger": "Past", ++ "medium_danger": "Oʻrtacha", ++ "neutral_danger": "Neytral", ++ "notified": "Xabar berildi", ++ "qhandler_success": "Soʻrov tizimga muvaffaqiyatli yuborildi. Endi oynani yopishingiz mumkin.", ++ "qid": "Rspamd QID", ++ "qinfo": "Karantin tizimi rad etilgan xatni (joʻnatuvchiga xat yetkazib berilgandek taassurot bermay) hamda pochta qutisining Junk papkasiga nusxa sifatida yetkazib berilgan xatni maʼlumotlar bazasiga saqlaydi.\r\n
\"Spam sifatida oʻrgatish va oʻchirish\" xabarni Bayesian teoremasi orqali spam sifatida oʻrgatadi va kelajakda oʻxshash xabarlarni rad etish uchun fuzzy hashlarni hisoblaydi.\r\n
Bir nechta xabarlarni oʻrgatish — tizimingizga qarab — vaqt talab qilishi mumkinligini unutmang.
Qora roʻyxatdagi elementlar karantindan istisno qilinadi.", ++ "qitem": "Karantin elementi", ++ "quarantine": "Karantin", ++ "quick_actions": "Amallar", ++ "quick_delete_link": "Tezkor oʻchirish havolasini ochish", ++ "quick_info_link": "Maʼlumot havolasini ochish", ++ "quick_release_link": "Tezkor chiqarish havolasini ochish", ++ "rcpt": "Qabul qiluvchi", ++ "received": "Qabul qilingan", ++ "recipients": "Qabul qiluvchilar", ++ "refresh": "Yangilash", ++ "rejected": "Rad etilgan", ++ "release": "Chiqarish", ++ "release_body": "Xabaringizni ushbu xabarga eml fayl sifatida ilova qildik.", ++ "release_subject": "Potensial xavfli karantin elementi %s", ++ "remove": "Olib tashlash", ++ "rewrite_subject": "Mavzuni qayta yozish", ++ "rspamd_result": "Rspamd natijasi", ++ "sender": "Joʻnatuvchi (SMTP)", ++ "sender_header": "Joʻnatuvchi (\"From\" sarlavhasi)", ++ "settings_info": "Karantinga olinadigan maksimal elementlar soni: %s
Maksimal e-pochta oʻlchami: %s MiB", ++ "show_item": "Elementni koʻrsatish", ++ "spam": "Spam", ++ "spam_score": "Baho", ++ "subj": "Mavzu", ++ "table_size": "Jadval oʻlchami", ++ "table_size_show_n": "%s ta element koʻrsatish", ++ "text_from_html_content": "Mazmun (oʻzgartirilgan html)", ++ "text_plain_content": "Mazmun (text/plain)", ++ "toggle_all": "Hammasini almashtirish", ++ "type": "Tur" ++ }, ++ "queue": { ++ "delete": "Hammasini oʻchirish", ++ "flush": "Navbatni tozalash", ++ "info": "Pochta navbati yetkazib berilishini kutayotgan barcha xatlarni oʻz ichiga oladi. Agar e-pochta uzoq vaqt davomida pochta navbatida tursa, u tizim tomonidan avtomatik ravishda oʻchiriladi.
Tegishli xatning xato xabari xat nima uchun yetkazib berilmaganligi haqida maʼlumot beradi.", ++ "legend": "Pochta navbati amallari funksiyalari:", ++ "ays": "Iltimos, joriy navbatdagi barcha elementlarni oʻchirishni tasdiqlang.", ++ "deliver_mail": "Yetkazib berish", ++ "deliver_mail_legend": "Tanlangan xatlarni qayta yetkazib berishga harakat qiladi.", ++ "hold_mail": "Ushlab turish", ++ "hold_mail_legend": "Tanlangan xatlarni ushlab turadi. (Keyingi yetkazib berish urinishlarining oldini oladi)", ++ "queue_manager": "Navbat menejeri", ++ "show_message": "Xabarni koʻrsatish", ++ "unban": "navbatdan blokdan chiqarish", ++ "unhold_mail": "Ushlab turishni bekor qilish", ++ "unhold_mail_legend": "Tanlangan xatlarni yetkazib berish uchun chiqaradi. (Avval ushlab turish talab qilinadi)" ++ }, ++ "ratelimit": { ++ "disabled": "Oʻchirilgan", ++ "second": "xabarlar / soniya", ++ "minute": "xabarlar / daqiqa", ++ "hour": "xabarlar / soat", ++ "day": "xabarlar / kun" ++ }, ++ "start": { ++ "help": "Yordam panelini koʻrsatish/yashirish", ++ "imap_smtp_server_auth_info": "Iltimos, toʻliq e-pochta manzilingiz va PLAIN autentifikatsiya mexanizmidan foydalaning.
\r\nKirish maʼlumotlaringiz server tomonidagi majburiy shifrlash orqali shifrlanadi." ++ }, ++ "success": { ++ "acl_saved": "%s obyekti uchun ACL saqlandi", ++ "admin_added": "Administrator %s qoʻshildi", ++ "admin_api_modified": "API ga oʻzgarishlar saqlandi", ++ "admin_modified": "Administrator oʻzgarishlari saqlandi", ++ "admin_removed": "Administrator %s olib tashlandi", ++ "alias_added": "Taxallus manzili %s (%d) qoʻshildi", ++ "alias_domain_removed": "Taxallus domeni %s olib tashlandi", ++ "alias_modified": "Taxallus manzili %s ga oʻzgarishlar saqlandi", ++ "alias_removed": "Taxallus %s olib tashlandi", ++ "aliasd_added": "Taxallus domeni %s qoʻshildi", ++ "aliasd_modified": "Taxallus domeni %s ga oʻzgarishlar saqlandi", ++ "app_links": "Ilova havolalariga oʻzgarishlar saqlandi", ++ "app_passwd_added": "Yangi ilova paroli qoʻshildi", ++ "app_passwd_removed": "Ilova paroli ID %s olib tashlandi", ++ "bcc_deleted": "BCC xaritasi yozuvlari oʻchirildi: %s", ++ "bcc_edited": "BCC xaritasi yozuvi %s tahrirlandi", ++ "bcc_saved": "BCC xaritasi yozuvi saqlandi", ++ "cors_headers_edited": "CORS sozlamalari saqlandi", ++ "custom_login_modified": "Kirishni sozlash muvaffaqiyatli saqlandi", ++ "db_init_complete": "Maʼlumotlar bazasini ishga tushirish tugadi", ++ "delete_filter": "Filtr ID %s oʻchirildi", ++ "delete_filters": "Filtrlar oʻchirildi: %s", ++ "deleted_syncjob": "Sinxronizatsiya vazifasi ID %s oʻchirildi", ++ "deleted_syncjobs": "Sinxronizatsiya vazifalari oʻchirildi: %s", ++ "dkim_added": "DKIM kaliti %s saqlandi", ++ "domain_add_dkim_available": "DKIM kaliti allaqachon mavjud edi", ++ "dkim_duplicated": "%s domeni uchun DKIM kaliti %s ga nusxalandi", ++ "dkim_removed": "DKIM kaliti %s olib tashlandi", ++ "domain_added": "Domen %s qoʻshildi", ++ "domain_admin_added": "Domen administratori %s qoʻshildi", ++ "domain_admin_modified": "Domen administratori %s ga oʻzgarishlar saqlandi", ++ "domain_admin_removed": "Domen administratori %s olib tashlandi", ++ "domain_footer_modified": "Domen pastki qismi %s ga oʻzgarishlar saqlandi", ++ "domain_modified": "Domen %s ga oʻzgarishlar saqlandi", ++ "domain_removed": "Domen %s olib tashlandi", ++ "dovecot_restart_success": "Dovecot muvaffaqiyatli qayta ishga tushirildi", ++ "eas_reset": "%s foydalanuvchisi uchun ActiveSync qurilmalari tiklandi", ++ "f2b_banlist_refreshed": "Banlist ID muvaffaqiyatli yangilandi.", ++ "f2b_modified": "Fail2ban parametrlariga oʻzgarishlar saqlandi", ++ "forwarding_host_added": "Yoʻnaltirish xosti %s qoʻshildi", ++ "forwarding_host_removed": "Yoʻnaltirish xosti %s olib tashlandi", ++ "global_filter_written": "Filtr faylga muvaffaqiyatli yozildi", ++ "hash_deleted": "Hash oʻchirildi", ++ "iam_test_connection": "Ulanish muvaffaqiyatli", ++ "ip_check_opt_in_modified": "IP tekshiruvi muvaffaqiyatli saqlandi", ++ "item_deleted": "Element %s muvaffaqiyatli oʻchirildi", ++ "item_released": "Element %s chiqarildi", ++ "items_deleted": "Element %s muvaffaqiyatli oʻchirildi", ++ "items_released": "Tanlangan elementlar chiqarildi", ++ "learned_ham": "ID %s ham sifatida muvaffaqiyatli oʻrgatildi", ++ "license_modified": "Litsenziyaga oʻzgarishlar saqlandi", ++ "logged_in_as": "%s sifatida tizimga kirildi", ++ "mailbox_added": "Pochta qutisi %s qoʻshildi", ++ "mailbox_modified": "Pochta qutisi %s ga oʻzgarishlar saqlandi", ++ "mailbox_removed": "Pochta qutisi %s olib tashlandi", ++ "mailbox_renamed": "Pochta qutisi %s dan %s ga qayta nomlandi", ++ "nginx_reloaded": "Nginx qayta yuklandi", ++ "object_modified": "Obyekt %s ga oʻzgarishlar saqlandi", ++ "password_policy_saved": "Parol siyosati muvaffaqiyatli saqlandi", ++ "password_changed_success": "Parol muvaffaqiyatli oʻzgartirildi", ++ "pushover_settings_edited": "Pushover sozlamalari muvaffaqiyatli oʻrnatildi, iltimos maʼlumotlarni tekshiring.", ++ "qlearn_spam": "Xabar ID %s spam sifatida oʻrgatildi va oʻchirildi", ++ "queue_command_success": "Navbat buyrugʻi muvaffaqiyatli yakunlandi", ++ "recipient_map_entry_deleted": "Qabul qiluvchi xaritasi ID %s oʻchirildi", ++ "recipient_map_entry_saved": "Qabul qiluvchi xaritasi yozuvi \"%s\" saqlandi", ++ "recovery_email_sent": "Tiklash e-pochtasi %s ga yuborildi", ++ "relayhost_added": "Xarita yozuvi %s qoʻshildi", ++ "relayhost_removed": "Xarita yozuvi %s olib tashlandi", ++ "reset_main_logo": "Standart logotipga qaytarildi", ++ "resource_added": "Resurs %s qoʻshildi", ++ "resource_modified": "Pochta qutisi %s ga oʻzgarishlar saqlandi", ++ "resource_removed": "Resurs %s olib tashlandi", ++ "rl_saved": "%s obyekti uchun tezlik chegarasi saqlandi", ++ "rspamd_ui_pw_set": "Rspamd UI paroli muvaffaqiyatli oʻrnatildi", ++ "saved_settings": "Sozlamalar saqlandi", ++ "settings_map_added": "Sozlamalar xaritasi yozuvi qoʻshildi", ++ "settings_map_removed": "Sozlamalar xaritasi ID %s olib tashlandi", ++ "sogo_profile_reset": "%s foydalanuvchisi uchun SOGo profili tiklandi", ++ "template_added": "Shablon %s qoʻshildi", ++ "template_modified": "Shablon %s ga oʻzgarishlar saqlandi", ++ "template_removed": "Shablon ID %s oʻchirildi", ++ "tls_policy_map_entry_deleted": "TLS siyosati xaritasi ID %s oʻchirildi", ++ "tls_policy_map_entry_saved": "TLS siyosati xaritasi yozuvi \"%s\" saqlandi", ++ "ui_texts": "UI matnlariga oʻzgarishlar saqlandi", ++ "upload_success": "Fayl muvaffaqiyatli yuklandi", ++ "verified_fido2_login": "FIDO2 kirishi tasdiqlandi", ++ "verified_totp_login": "TOTP kirishi tasdiqlandi", ++ "verified_webauthn_login": "WebAuthn kirishi tasdiqlandi", ++ "verified_yotp_login": "Yubico OTP kirishi tasdiqlandi" ++ }, ++ "tfa": { ++ "authenticators": "Autentifikatorlar", ++ "api_register": "%s Yubico Cloud API dan foydalanadi. Iltimos, kalitingiz uchun API kalitini bu yerdan oling", ++ "confirm": "Tasdiqlash", ++ "confirm_totp_token": "Iltimos, yaratilgan tokenni kiritib oʻzgarishlaringizni tasdiqlang", ++ "delete_tfa": "TFA ni oʻchirish", ++ "disable_tfa": "Keyingi muvaffaqiyatli kirishgacha TFA ni oʻchirish", ++ "force_tfa": "Kirishda 2FA roʻyxatdan oʻtkazishni majburlash", ++ "force_tfa_info": "Foydalanuvchidan panelga kirishdan oldin ikki faktorli autentifikatsiyani sozlash talab qilinadi.", ++ "setup_title": "Ikki faktorli autentifikatsiya talab qilinadi", ++ "setup_required": "Hisobingiz ikki faktorli autentifikatsiyani talab qiladi. Davom etish uchun 2FA usulini sozlang.", ++ "cancel_setup": "Bekor qilish va chiqish", ++ "enter_qr_code": "Agar qurilmangiz QR kodlarni skanerlay olmasa, TOTP kodingiz", ++ "error_code": "Xato kodi", ++ "init_webauthn": "Ishga tushirilmoqda, iltimos kuting...", ++ "key_id": "Qurilmangiz uchun identifikator", ++ "key_id_totp": "Kalitingiz uchun identifikator", ++ "none": "Oʻchirish", ++ "reload_retry": "- (xato davom etsa, brauzerni qayta yuklang)", ++ "scan_qr_code": "Iltimos, quyidagi kodni autentifikator ilovangiz bilan skanerlang yoki kodni qoʻlda kiriting.", ++ "select": "Iltimos, tanlang", ++ "set_tfa": "Ikki faktorli autentifikatsiya usulini oʻrnatish", ++ "start_webauthn_validation": "Tekshiruvni boshlash", ++ "tfa": "Ikki faktorli autentifikatsiya", ++ "tfa_token_invalid": "TFA tokeni noto'g'ri", ++ "totp": "Vaqt asosidagi OTP (Google Authenticator, Authy va h.k.)", ++ "u2f_deprecated": "Sizning kalitingiz eskirgan U2F usulidan foydalanib roʻyxatdan oʻtkazilganga oʻxshaydi. Biz siz uchun ikki faktorli autentifikatsiyani oʻchirib qoʻyamiz va kalitingizni oʻchiramiz.", ++ "u2f_deprecated_important": "Iltimos, kalitingizni admin panelida yangi WebAuthn usuli bilan roʻyxatdan oʻtkazing.", ++ "webauthn": "WebAuthn autentifikatsiya", ++ "waiting_usb_auth": "USB qurilmasi kutilmoqda...

Iltimos, hozir USB qurilmangizdagi tugmani bosing.", ++ "waiting_usb_register": "USB qurilmasi kutilmoqda...

Iltimos, yuqorida parolingizni kiriting va USB qurilmangizdagi tugmani bosib roʻyxatga olinishingizni tasdiqlang.", ++ "yubi_otp": "Yubico OTP autentifikatsiya" ++ }, ++ "user": { ++ "action": "Amal", ++ "active": "Faol", ++ "active_sieve": "Faol filtr", ++ "advanced_settings": "Kengaytirilgan sozlamalar", ++ "alias": "Taxallus", ++ "alias_create_random": "Tasodifiy taxallus yaratish", ++ "alias_extend_all": "Taxalluslarni 1 soatga uzaytirish", ++ "alias_full_date": "d.m.Y, H:i:s T", ++ "alias_remove_all": "Barcha taxalluslarni olib tashlash", ++ "alias_select_validity": "Amal qilish muddati", ++ "alias_time_left": "Qolgan vaqt", ++ "alias_valid_until": "Amal qiladi (gacha)", ++ "aliases_also_send_as": "Foydalanuvchi sifatida ham joʻnatishga ruxsat berilgan", ++ "aliases_send_as_all": "Quyidagi domen(lar) va ularning taxallus domenlari uchun joʻnatuvchi kirishini tekshirmaslik", ++ "app_hint": "Ilova parollari sizning IMAP, SMTP, CalDAV, CardDAV va EAS kirishi uchun muqobil parollardir. Foydalanuvchi nomi oʻzgarmaydi. SOGo webmail ilova parollari orqali mavjud emas.", ++ "allowed_protocols": "Ruxsat etilgan protokollar", ++ "app_name": "Ilova nomi", ++ "app_passwds": "Ilova parollari", ++ "apple_connection_profile": "Apple ulanish profili", ++ "apple_connection_profile_complete": "Bu ulanish profili Apple qurilmasi uchun IMAP va SMTP parametrlari hamda CalDAV (kalendarlar) va CardDAV (kontaktlar) yoʻllarini oʻz ichiga oladi.", ++ "apple_connection_profile_mailonly": "Bu ulanish profili Apple qurilmasi uchun IMAP va SMTP konfiguratsiya parametrlarini oʻz ichiga oladi.", ++ "apple_connection_profile_with_app_password": "Yangi ilova paroli yaratiladi va profilga qoʻshiladi, shunda qurilmangizni sozlashda parol kiritish kerak boʻlmaydi. Iltimos, faylni ulashmang, chunki u pochta qutingizga toʻliq kirish huquqini beradi.", ++ "attribute": "Atribut", ++ "authentication": "Autentifikatsiya", ++ "change_password": "Parolni oʻzgartirish", ++ "change_password_hint_app_passwords": "Hisobingizda %d ta ilova paroli mavjud va ular oʻzgartirilmaydi. Ularni boshqarish uchun Ilova parollari yorligʻiga oʻting.", ++ "clear_recent_successful_connections": "Koʻrilgan muvaffaqiyatli ulanishlarni tozalash", ++ "client_configuration": "E-pochta mijozlari va smartfonlar uchun konfiguratsiya qoʻllanmalarini koʻrsatish", ++ "create_app_passwd": "Ilova paroli yaratish", ++ "create_syncjob": "Yangi sinxronizatsiya vazifasi yaratish", ++ "created_on": "Yaratilgan sana", ++ "daily": "Kunlik", ++ "day": "kun", ++ "description": "Tavsif", ++ "delete_ays": "Iltimos, oʻchirish jarayonini tasdiqlang.", ++ "direct_aliases": "Toʻgʻridan-toʻgʻri taxallus manzillari", ++ "direct_aliases_desc": "Toʻgʻridan-toʻgʻri taxallus manzillariga spam filtri va TLS siyosati sozlamalari taʼsir qiladi.", ++ "direct_protocol_access": "Bu pochta qutisi foydalanuvchisi quyidagi protokollar va ilovalarga toʻgʻridan-toʻgʻri, tashqi kirishga ega. Bu sozlama administratoringiz tomonidan boshqariladi. Maxsus protokollar va ilovalarga kirishga ruxsat berish uchun ilova parollarini yaratish mumkin.
\"Webmail\" tugmasi SOGo ga yagona kirish (SSO) imkonini beradi va doimo mavjud.", ++ "eas_reset": "ActiveSync qurilma keshini tiklash", ++ "eas_reset_help": "Koʻp hollarda qurilma keshini tiklash buzilgan ActiveSync profilini tiklashga yordam beradi.
Diqqat: Barcha elementlar qayta yuklab olinadi!", ++ "eas_reset_now": "Hozir tiklash", ++ "edit": "Tahrirlash", ++ "email": "E-pochta", ++ "email_and_dav": "E-pochta, kalendarlar va kontaktlar", ++ "empty": "Natijalar yoʻq", ++ "encryption": "Shifrlash", ++ "excludes": "Istisnolar", ++ "expire_in": "Tugaydi", ++ "expire_never": "Hech qachon tugamasin", ++ "fido2_webauthn": "FIDO2/WebAuthn", ++ "forever": "Abadiy", ++ "force_pw_update": "Guruh dasturi xizmatlariga kirish uchun siz yangi parol oʻrnatishingiz kerak.", ++ "from": "dan", ++ "generate": "yaratish", ++ "hour": "soat", ++ "hourly": "Soatlik", ++ "hours": "soat", ++ "in_use": "Foydalanilmoqda", ++ "interval": "Oraliq", ++ "is_catch_all": "Domen(lar) uchun Hammasini-qabul qilish", ++ "last_mail_login": "Oxirgi pochta kirishi", ++ "last_pw_change": "Oxirgi parol oʻzgarishi", ++ "last_run": "Oxirgi ishga tushirilgan", ++ "last_ui_login": "Oxirgi UI kirishi", ++ "loading": "Yuklanmoqda...", ++ "login_history": "Kirish tarixi", ++ "mailbox": "Pochta qutisi", ++ "mailbox_details": "Tafsilotlar", ++ "mailbox_general": "Umumiy", ++ "mailbox_settings": "Sozlamalar", ++ "messages": "xabarlar", ++ "month": "oy", ++ "months": "oy", ++ "never": "Hech qachon", ++ "new_password": "Yangi parol", ++ "new_password_repeat": "Tasdiqlash paroli (takrorlang)", ++ "no_active_filter": "Faol filtr mavjud emas", ++ "no_last_login": "Oxirgi UI kirishi haqida maʼlumot yoʻq", ++ "no_record": "Yozuv yoʻq", ++ "open_logs": "Jurnallarni ochish", ++ "open_webmail_sso": "Webmail", ++ "overview": "Umumiy koʻrinish", ++ "password": "Parol", ++ "password_now": "Joriy parol (oʻzgarishlarni tasdiqlang)", ++ "pw_update_required": "Hisobingiz parol oʻzgartirishni talab qiladi. Davom etish uchun yangi parolni oʻrnating.", ++ "password_repeat": "Parol (takrorlang)", ++ "password_reset_info": "Agar parolni tiklash uchun e-pochta kiritilmagan boʻlsa, bu funksiyadan foydalanib boʻlmaydi.", ++ "protocols": "Protokollar", ++ "pushover_evaluate_x_prio": "Yuqori muhimlikdagi xatni eskalatsiya qilish [X-Priority: 1]", ++ "pushover_info": "Push bildirishnoma sozlamalari %s ga taxalluslar bilan birga (umumiy, umumiy boʻlmagan, teglangan) yetkazib beriladigan barcha toza (spam boʻlmagan) xatlarga qoʻllaniladi.", ++ "pushover_only_x_prio": "Faqat yuqori muhimlikdagi xatlarni koʻrib chiqish [X-Priority: 1]", ++ "pushover_sender_array": "Quyidagi joʻnatuvchi e-pochta manzillarini koʻrib chiqish (vergul bilan ajratilgan)", ++ "pushover_sender_regex": "Joʻnatuvchilarni quyidagi regex orqali mos kelishini tekshirish", ++ "pushover_text": "Bildirishnoma matni", ++ "pushover_title": "Bildirishnoma sarlavhasi", ++ "pushover_sound": "Tovush", ++ "pushover_vars": "Joʻnatuvchi filtri belgilanmagan boʻlsa, barcha xatlar koʻrib chiqiladi.
Regex filtrlari va aniq joʻnatuvchi tekshiruvlari alohida belgilanishi mumkin va ketma-ket koʻrib chiqiladi. Ular bir-biriga bogʻliq emas.
Matn va sarlavha uchun ishlatiladigan oʻzgaruvchilar (ma'lumotlarni himoya qilish siyosatiga e'tibor bering)", ++ "pushover_verify": "Maʼlumotlarni tekshirish", ++ "pw_recovery_email": "Parolni tiklash e-pochtasi", ++ "q_add_header": "Junk papkasi", ++ "q_all": "Barcha turkumlar", ++ "q_reject": "Rad etilgan", ++ "quarantine_category": "Karantin bildirishnoma turkumi", ++ "quarantine_category_info": "\"Rad etilgan\" bildirishnoma turkumi rad etilgan xatlarni oʻz ichiga oladi, \"Junk papkasi\" esa Junk papkasiga joylashtirilgan xatlar haqida foydalanuvchini xabardor qiladi.", ++ "quarantine_notification": "Karantin bildirishnomalari", ++ "quarantine_notification_info": "Bildirishnoma yuborilgandan keyin elementlar \"xabar berildi\" deb belgilanadi va bu element uchun keyingi bildirishnomalar yuborilmaydi.", ++ "recent_successful_connections": "Koʻrilgan muvaffaqiyatli ulanishlar", ++ "remove": "Olib tashlash", ++ "running": "Ishlamoqda", ++ "save": "Oʻzgarishlarni saqlash", ++ "save_changes": "Oʻzgarishlarni saqlash", ++ "sender_acl_disabled": "Joʻnatuvchi tekshiruvi oʻchirilgan", ++ "shared_aliases": "Umumiy taxallus manzillari", ++ "shared_aliases_desc": "Umumiy taxalluslarga foydalanuvchining maxsus sozlamalari (spam filtri yoki shifrlash siyosati kabi) taʼsir qilmaydi. Mos spam filtrlarini faqat administrator domen boʻyicha siyosat sifatida sozlashi mumkin.", ++ "show_sieve_filters": "Faol foydalanuvchi sieve filtrini koʻrsatish", ++ "sogo_profile_reset": "SOGo profilini tiklash", ++ "sogo_profile_reset_help": "Bu foydalanuvchining SOGo profilini yoʻq qiladi va barcha kontakt va kalendar maʼlumotlarini qaytarib boʻlmas tarzda oʻchiradi.", ++ "sogo_profile_reset_now": "Profilni hozir tiklash", ++ "spam_aliases": "Spam e-pochta taxalluslari", ++ "spam_aliases_info": "Spam taxallusi — bu haqiqiy e-pochta manzillarini himoya qilish uchun ishlatilishi mumkin boʻlgan vaqtinchalik e-pochta manzilidir.
Ixtiyoriy ravishda muddat tugash vaqtini belgilash mumkin, shunda taxallus belgilangan davrdan keyin avtomatik oʻchirib qoʻyiladi, suiisteʼmol qilingan yoki tarqalib ketgan manzillarni samarali tarzda chiqarib tashlaydi.", ++ "spam_score_reset": "Server standartiga qaytarish", ++ "spamfilter": "Spam filtri", ++ "spamfilter_behavior": "Baholash", ++ "spamfilter_bl": "Qora roʻyxat", ++ "spamfilter_bl_desc": "Qora roʻyxatdagi e-pochta manzillari har doim spam sifatida tasniflanadi va rad etiladi. Rad etilgan xat karantinga nusxalanmaydi. Joker belgilar ishlatilishi mumkin. Filtr faqat toʻgʻridan-toʻgʻri taxalluslarga (bitta maqsad pochta qutisiga ega taxalluslarga) qoʻllaniladi, hammasini-qabul qilish taxalluslari va pochta qutisining oʻzi istisno qilinadi.", ++ "spamfilter_default_score": "Standart qiymatlar", ++ "spamfilter_green": "Yashil: bu xabar spam emas", ++ "spamfilter_hint": "Birinchi qiymat \"past spam bahosi\"ni tavsiflaydi, ikkinchisi \"yuqori spam bahosi\"ni ifodalaydi.", ++ "spamfilter_red": "Qizil: bu xabar spam va server tomonidan rad etiladi", ++ "spamfilter_table_action": "Amal", ++ "spamfilter_table_add": "Element qoʻshish", ++ "spamfilter_table_domain_policy": "n/a (domen siyosati)", ++ "spamfilter_table_empty": "Koʻrsatish uchun ma'lumot yoʻq", ++ "spamfilter_table_remove": "olib tashlash", ++ "spamfilter_table_rule": "Qoida", ++ "spamfilter_wl": "Oq roʻyxat", ++ "spamfilter_wl_desc": "Oq roʻyxatdagi e-pochta manzillari hech qachon spam sifatida tasniflanmaydi. Joker belgilar ishlatilishi mumkin. Filtr faqat toʻgʻridan-toʻgʻri taxalluslarga (bitta maqsad pochta qutisiga ega taxalluslarga) qoʻllaniladi, hammasini-qabul qilish taxalluslari va pochta qutisining oʻzi istisno qilinadi.", ++ "spamfilter_yellow": "Sariq: bu xabar spam boʻlishi mumkin, spam sifatida belgilanadi va Junk papkangizga koʻchiriladi", ++ "status": "Holat", ++ "sync_jobs": "Sinxronizatsiya vazifalari", ++ "syncjob_check_log": "Jurnalni tekshirish", ++ "syncjob_last_run_result": "Oxirgi ishga tushirilgan natija", ++ "syncjob_EX_OK": "Muvaffaqiyatli", ++ "syncjob_EXIT_CONNECTION_FAILURE": "Ulanish muammosi", ++ "syncjob_EXIT_TLS_FAILURE": "Shifrlangan ulanish bilan muammo", ++ "syncjob_EXIT_AUTHENTICATION_FAILURE": "Autentifikatsiya muammosi", ++ "syncjob_EXIT_OVERQUOTA": "Maqsad pochta qutisi kvotadan oshib ketdi", ++ "syncjob_EXIT_CONNECTION_FAILURE_HOST1": "Masofaviy serverga ulanib boʻlmadi", ++ "syncjob_EXIT_AUTHENTICATION_FAILURE_USER1": "Notoʻgʻri foydalanuvchi nomi yoki parol", ++ "tag_handling": "Teglangan xat uchun ishlovni oʻrnatish", ++ "tag_help_example": "Teglangan e-pochta manzili misoli: me+Facebook@example.org", ++ "tag_help_explain": "Subpapkada: tegga qarab nomlangan yangi subpapka INBOX ostida yaratiladi (\"INBOX/Facebook\").
\r\nMavzuda: teg nomi xatning mavzusiga oldindan qoʻshiladi, misol: \"[Facebook] Mening yangiliklarim\".", ++ "tag_in_none": "Hech narsa qilmaslik", ++ "tag_in_subfolder": "Subpapkada", ++ "tag_in_subject": "Mavzuda", ++ "text": "Matn", ++ "tfa_info": "Ikki faktorli autentifikatsiya hisobingizni himoya qilishga yordam beradi. Uni yoqsangiz, ikki faktorli autentifikatsiyani qoʻllab-quvvatlamaydigan ilovalar yoki xizmatlarga (masalan, pochta mijozlari) kirish uchun ilova parollari kerak boʻladi.", ++ "title": "Sarlavha", ++ "tls_enforce_in": "Kiruvchi TLS ni majburlash", ++ "tls_enforce_out": "Chiquvchi TLS ni majburlash", ++ "tls_policy": "Shifrlash siyosati", ++ "tls_policy_warning": "Diqqat: Agar shifrlangan pochta transferini majburlashga qaror qilsangiz, e-pochtalarni yoʻqotishingiz mumkin.
Siyosatga mos kelmaydigan xabarlar pochta tizimi tomonidan qatʼiy muvaffaqiyatsizlik bilan qaytariladi.
Bu variant sizning asosiy e-pochta manzilingiz (kirish nomingiz), taxallus domenlaridan olingan barcha manzillar va faqat ushbu pochta qutisi maqsad sifatida boʻlgan taxallus manzillariga qoʻllaniladi.", ++ "user_settings": "Foydalanuvchi sozlamalari", ++ "username": "Foydalanuvchi nomi", ++ "value": "Qiymat", ++ "verify": "Tasdiqlash", ++ "waiting": "Kutilmoqda", ++ "week": "hafta", ++ "weekly": "Haftalik", ++ "weeks": "hafta", ++ "with_app_password": "ilova paroli bilan", ++ "year": "yil", ++ "years": "yil" ++ }, ++ "warning": { ++ "cannot_delete_self": "Tizimga kirgan foydalanuvchini oʻchirib boʻlmaydi", ++ "domain_added_sogo_failed": "Domen qoʻshildi, ammo SOGoni qayta ishga tushirib boʻlmadi, iltimos server jurnallaringizni tekshiring.", ++ "dovecot_restart_failed": "Dovecot qayta ishga tushirib boʻlmadi, iltimos jurnallarni tekshiring", ++ "fuzzy_learn_error": "Fuzzy hash oʻrgatish xatosi: %s", ++ "hash_not_found": "Hash topilmadi yoki allaqachon oʻchirilgan", ++ "ip_invalid": "Notoʻgʻri IP oʻtkazib yuborildi: %s", ++ "is_not_primary_alias": "Asosiy boʻlmagan taxallus oʻtkazib yuborildi: %s", ++ "no_active_admin": "Oxirgi faol administratorni oʻchirib boʻlmaydi", ++ "quota_exceeded_scope": "Domen kvotasi oshib ketdi: Bu domen doirasida faqat cheksiz pochta qutilari yaratilishi mumkin.", ++ "session_token": "Forma tokeni noto'g'ri: Token mos kelmadi", ++ "session_ua": "Forma tokeni noto'g'ri: User-Agent tekshiruvi xatosi" ++ } ++} diff --git a/tasks/mailcow__mailcow-dockerized-7224/solution/solve.sh b/tasks/mailcow__mailcow-dockerized-7224/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7224/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo 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-7224/task.toml b/tasks/mailcow__mailcow-dockerized-7224/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..aa8d0bda6e7d27df261622587dff2b272fd7a312 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7224/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/mailcow__mailcow-dockerized-7224" +description = "Add Uzbek language" + +[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 = "a8e945f3da89b98258a01b5137ca1a9dc72d67d9" +reference = "https://github.com/mailcow/mailcow-dockerized/pull/7224" +source_access = "auto" +built_at = "2026-11-16T16:09:53.200189+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:46761fd207b2f253ef8202c80dd7b6cc013b6cf3ef6909a18434ba4c13ffd3b0" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-05-13T14:42:39Z" +diff_format = "unified" +context_files = [ + "data/web/inc/vars.inc.php", + "data/web/lang/lang.uz-uz.json", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 1441 +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.451485+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:db4f23a1d1b82ab4b5a81ab2b1ee2d8f4f71c9144aaf4dc836db5bccd712fcb8" +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-7224/tests/capture.py b/tasks/mailcow__mailcow-dockerized-7224/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7224/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture 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-7224/tests/instruction.md b/tasks/mailcow__mailcow-dockerized-7224/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8f716493e8287e127d87f91eccf1958142bd5526 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7224/tests/instruction.md @@ -0,0 +1,51 @@ +# Issue + +**Title:** Add Uzbek language + +## 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 Uzbek (Oʻzbekcha) as a new UI language for mailcow. + +- Registers `uz-uz => Oʻzbekcha (Uzbek)` in `$AVAILABLE_LANGUAGES` (`data/web/inc/vars.inc.php`), placed alphabetically after `uk-ua`. +- Adds a full translation file `data/web/lang/lang.uz-uz.json` covering all 23 top-level sections and all 1386 translatable strings from `lang.en-gb.json`. + +Notes on the translation: +- Uses modern Uzbek Latin script (the official script of Uzbekistan since 1993), including the proper `oʻ` / `gʻ` characters (e.g. `Oʻzbekcha`, `qoʻshish`). +- Preserves all JSON keys, HTML markup, format specifiers (`%s`, `%d`), placeholders (`{{var}}`, `_START_`, `_END_`, `_TOTAL_`, `_MAX_`, `_MENU_`), and ``/``/`` blocks unchanged. +- Technical terms (DKIM, DMARC, TLS, SMTP, IMAP, MX, OAuth2, Rspamd, SOGo, Fail2ban, FIDO2, WebAuthn, TOTP, etc.) are left untranslated to match common Uzbek IT usage. + +### Affected Containers + +- nginx-mailcow (UI/PHP files served by the web container only — no other container modified) + +## Did you run tests? + +### What did you tested? + +- Validated `lang.uz-uz.json` syntax with `jq empty` — file parses cleanly. +- Compared all top-level section keys between `lang.en-gb.json` and `lang.uz-uz.json` (`acl`, `add`, `admin`, `danger`, `datatables`, `debug`, `diagnostics`, `edit`, `fido2`, `footer`, `header`, `info`, `login`, `mailbox`, `oauth2`, `quarantine`, `queue`, `ratelimit`, `start`, `success`, `tfa`, `user`, `warning`) — `diff` reports no difference. +- Compared every sub-key inside each section against the English file — no missing or extra keys. +- Counted translatable string leaves with `jq` — both files have **1386** string entries. +- Verified that placeholders and HTML markup were preserved (no stripped ``, ``, ``, `%s`, `%d`, `{{...}}` tokens). +- Confirmed `vars.inc.php` change is a single-line addition matching the surrounding PHP array style; the language code follows the IETF tag convention used by the other entries. + +### What were the final results? (Awaited, got) + +- **Awaited:** New `uz-uz` option appears in the language switcher and the UI displays Uzbek strings when selected; existing locales continue to work unchanged. +- **Got:** JSON validation passes, key parity with `en-gb` is 1:1, and `vars.inc.php` cleanly registers the new locale. No regressions expected in other languages since only an additive change to `$AVAILABLE_LANGUAGES` and a new translation file are introduced. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `a8e945f3da89`. Edit files in place; the verifier captures your changes via `git diff` 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-7224/tests/oracle.patch b/tasks/mailcow__mailcow-dockerized-7224/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..149d4fb8498ddaadd8afa920e58a108633839f5d --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7224/tests/oracle.patch @@ -0,0 +1,1458 @@ +diff --git a/data/web/inc/vars.inc.php b/data/web/inc/vars.inc.php +index 2f4a4b07..cec402a9 100644 +--- a/data/web/inc/vars.inc.php ++++ b/data/web/inc/vars.inc.php +@@ -112,6 +112,7 @@ $AVAILABLE_LANGUAGES = array( + 'sv-se' => 'Svenska (Swedish)', + 'tr-tr' => 'Türkçe (Turkish)', + 'uk-ua' => 'Українська (Ukrainian)', ++ 'uz-uz' => 'Oʻzbekcha (Uzbek)', + 'vi-vn' => 'Tiếng Việt (Vietnamese)', + 'zh-cn' => '简体中文 (Simplified Chinese)', + 'zh-tw' => '繁體中文 (Traditional Chinese)', +diff --git a/data/web/lang/lang.uz-uz.json b/data/web/lang/lang.uz-uz.json +new file mode 100644 +index 00000000..a8d2ecf8 +--- /dev/null ++++ b/data/web/lang/lang.uz-uz.json +@@ -0,0 +1,1440 @@ ++{ ++ "acl": { ++ "alias_domains": "Taxallus domenlarini qoʻshish", ++ "app_passwds": "Ilova parollarini boshqarish", ++ "bcc_maps": "BCC xaritalari", ++ "delimiter_action": "Ajratuvchi amali", ++ "domain_desc": "Domen tavsifini oʻzgartirish", ++ "domain_relayhost": "Domen uchun relay xostni oʻzgartirish", ++ "eas_reset": "EAS qurilmalarini tiklash", ++ "extend_sender_acl": "Tashqi manzillar yordamida joʻnatuvchi ACL ni kengaytirishga ruxsat berish", ++ "filters": "Filtrlar", ++ "login_as": "Pochta qutisi foydalanuvchisi sifatida kirish", ++ "mailbox_relayhost": "Pochta qutisi uchun relay xostni oʻzgartirish", ++ "prohibited": "ACL tomonidan taqiqlangan", ++ "protocol_access": "Protokolga kirishni oʻzgartirish", ++ "pushover": "Pushover", ++ "pw_reset": "mailcow foydalanuvchi parolini tiklashga ruxsat berish", ++ "quarantine": "Karantin amallari", ++ "quarantine_attachments": "Karantindagi ilovalar", ++ "quarantine_category": "Karantin bildirishnoma turkumini oʻzgartirish", ++ "quarantine_notification": "Karantin bildirishnomalarini oʻzgartirish", ++ "ratelimit": "Tezlik chegarasi", ++ "recipient_maps": "Qabul qiluvchi xaritalari", ++ "smtp_ip_access": "SMTP uchun ruxsat etilgan xostlarni oʻzgartirish", ++ "sogo_access": "SOGo kirishini boshqarishga ruxsat berish", ++ "sogo_profile_reset": "SOGo profilini tiklash", ++ "spam_alias": "Vaqtinchalik taxalluslar", ++ "spam_policy": "Qora roʻyxat/Oq roʻyxat", ++ "spam_score": "Spam bahosi", ++ "syncjobs": "Sinxronizatsiya vazifalari", ++ "tls_policy": "TLS siyosati", ++ "unlimited_quota": "Pochta qutilari uchun cheksiz kvota" ++ }, ++ "add": { ++ "activate_filter_warn": "Faol belgilansa, boshqa barcha filtrlar oʻchirib qoʻyiladi.", ++ "active": "Faol", ++ "add": "Qoʻshish", ++ "add_domain_only": "Faqat domen qoʻshish", ++ "add_domain_restart": "Domen qoʻshish va SOGoni qayta ishga tushirish", ++ "alias_address": "Taxallus manzil(lar)i", ++ "alias_address_info": "Toʻliq e-pochta manzil(lar)i yoki @example.com — domenga keladigan barcha xabarlarni qabul qilish uchun (vergul bilan ajratilgan). Faqat mailcow domenlari.", ++ "alias_domain": "Taxallus domeni", ++ "alias_domain_info": "Faqat haqiqiy domen nomlari (vergul bilan ajratilgan).", ++ "app_name": "Ilova nomi", ++ "app_password": "Ilova paroli qoʻshish", ++ "app_passwd_protocols": "Ilova paroli uchun ruxsat etilgan protokollar", ++ "automap": "Papkalarni avtomatik xaritalashga harakat qilish (\"Sent items\", \"Sent\" => \"Sent\" va h.k.)", ++ "backup_mx_options": "Relay sozlamalari", ++ "bcc_dest_format": "BCC manzili bitta haqiqiy e-pochta manzili boʻlishi kerak.
Agar bir nechta manzilga nusxa joʻnatish kerak boʻlsa, taxallus yarating va shu yerda ishlating.", ++ "comment_info": "Maxfiy izoh foydalanuvchiga koʻrinmaydi, ommaviy izoh esa foydalanuvchi koʻrinishida ustiga sichqoncha kelganda maslahat sifatida koʻrsatiladi", ++ "custom_params": "Maxsus parametrlar", ++ "custom_params_hint": "Toʻgʻri: --param=xy, notoʻgʻri: --param xy", ++ "delete1": "Tugatilgach manbadan oʻchirish", ++ "delete2": "Manbada boʻlmagan xabarlarni manzildan oʻchirish", ++ "delete2duplicates": "Manzildagi dublikatlarni oʻchirish", ++ "description": "Tavsif", ++ "destination": "Manzil", ++ "disable_login": "Kirishni taqiqlash (kiruvchi pochta hali ham qabul qilinadi)", ++ "domain": "Domen", ++ "domain_matches_hostname": "%s domeni xost nomiga mos keladi", ++ "domain_quota_m": "Domenning umumiy kvotasi (MiB)", ++ "dry": "Sinxronizatsiyani simulyatsiya qilish", ++ "enc_method": "Shifrlash usuli", ++ "exclude": "Obyektlarni istisno qilish (regex)", ++ "full_name": "Toʻliq ism", ++ "gal": "Global manzillar roʻyxati", ++ "gal_info": "GAL domenning barcha obyektlarini oʻz ichiga oladi va hech bir foydalanuvchi tomonidan tahrirlanmaydi. Oʻchirilsa, SOGodagi bandlik maʼlumotlari yoʻqoladi! Oʻzgarishlarni qoʻllash uchun SOGoni qayta ishga tushiring.", ++ "generate": "yaratish", ++ "goto_ham": "ham sifatida oʻrgatish", ++ "goto_null": "Xatni jimgina rad etish", ++ "goto_spam": "spam sifatida oʻrgatish", ++ "hostname": "Xost", ++ "inactive": "Nofaol", ++ "internal": "Ichki", ++ "internal_info": "Ichki taxalluslarga faqat oʻz domeni yoki taxallus domenlaridan kirish mumkin.", ++ "sender_allowed": "Ushbu taxallus orqali joʻnatishga ruxsat berish", ++ "kind": "Turi", ++ "mailbox_quota_def": "Standart pochta qutisi kvotasi", ++ "mailbox_quota_m": "Bitta pochta qutisining maks. kvotasi (MiB)", ++ "mailbox_username": "Foydalanuvchi nomi (e-pochta manzilining chap qismi)", ++ "max_aliases": "Mumkin boʻlgan maks. taxalluslar", ++ "max_mailboxes": "Mumkin boʻlgan maks. pochta qutilari", ++ "mins_interval": "Soʻrov oraligʻi (daqiqa)", ++ "multiple_bookings": "Bir nechta bandlovlar", ++ "nexthop": "Keyingi nuqta", ++ "password": "Parol", ++ "password_repeat": "Tasdiqlash paroli (takrorlang)", ++ "port": "Port", ++ "post_domain_add": "Yangi domen qoʻshilgandan keyin SOGo konteyneri (\"sogo-mailcow\") qayta ishga tushirilishi kerak!

Bundan tashqari, domenning DNS sozlamalarini koʻrib chiqing. DNS sozlamalari tasdiqlangach, yangi domeningiz (autoconfig.<domain>, autodiscover.<domain>) uchun sertifikatlarni avtomatik yaratish uchun \"acme-mailcow\" konteynerini qayta ishga tushiring.
Bu qadam ixtiyoriy va har 24 soatda qayta urinib koʻriladi.", ++ "private_comment": "Maxfiy izoh", ++ "public_comment": "Ommaviy izoh", ++ "quota_mb": "Kvota (MiB)", ++ "relay_all": "Barcha qabul qiluvchilarni relay qilish", ++ "relay_all_info": "↪ Agar barcha qabul qiluvchilarni relay qilmaslikni tanlasangiz, relay qilinishi kerak boʻlgan har bir qabul qiluvchi uchun (\"koʻr\") pochta qutisi qoʻshishingiz kerak boʻladi.", ++ "relay_domain": "Ushbu domenni relay qilish", ++ "relay_transport_info": "
Maʼlumot
Bu domen uchun maxsus manzilga transport xaritalarini belgilashingiz mumkin. Agar oʻrnatilmagan boʻlsa, MX qidiruvi amalga oshiriladi.", ++ "relay_unknown_only": "Faqat mavjud boʻlmagan pochta qutilarini relay qilish. Mavjud pochta qutilari mahalliy yetkazib beriladi.", ++ "relayhost_wrapped_tls_info": "Iltimos, TLS-oʻralgan portlardan foydalanmang (asosan 465-portda).
\r\nO'ralmagan istalgan portdan foydalaning va STARTTLS chiqaring. TLS ni majburlash uchun TLS siyosatini \"TLS siyosati xaritalari\"da yaratish mumkin.", ++ "select": "Iltimos, tanlang...", ++ "select_domain": "Avval domenni tanlang", ++ "sieve_desc": "Qisqa tavsif", ++ "sieve_type": "Filtr turi", ++ "skipcrossduplicates": "Papkalararo dublikat xabarlarni oʻtkazib yuborish (birinchi kelgan, birinchi xizmatlanadi)", ++ "subscribeall": "Barcha papkalarga obuna boʻlish", ++ "syncjob": "Sinxronizatsiya vazifasi qoʻshish", ++ "syncjob_hint": "Parollar oddiy matn sifatida saqlanishini unutmang!", ++ "tags": "Teglar", ++ "target_address": "Yoʻnaltirish manzillari", ++ "target_address_info": "Toʻliq e-pochta manzil(lar)i (vergul bilan ajratilgan).", ++ "target_domain": "Maqsad domen", ++ "timeout1": "Masofaviy xostga ulanish vaqtining tugashi", ++ "timeout2": "Mahalliy xostga ulanish vaqtining tugashi", ++ "username": "Foydalanuvchi nomi", ++ "validate": "Tekshirish", ++ "validation_success": "Muvaffaqiyatli tekshirildi" ++ }, ++ "admin": { ++ "access": "Kirish", ++ "action": "Amal", ++ "activate_api": "API ni faollashtirish", ++ "activate_send": "Joʻnatish tugmasini faollashtirish", ++ "active": "Faol", ++ "active_rspamd_settings_map": "Faol sozlamalar xaritasi", ++ "add": "Qoʻshish", ++ "add_admin": "Administrator qoʻshish", ++ "add_domain_admin": "Domen administratorini qoʻshish", ++ "add_forwarding_host": "Yoʻnaltirish xosti qoʻshish", ++ "add_relayhost": "Joʻnatuvchiga bogʻliq transport qoʻshish", ++ "add_relayhost_hint": "Autentifikatsiya maʼlumotlari, agar boʻlsa, oddiy matn sifatida saqlanishini unutmang.", ++ "add_row": "Satr qoʻshish", ++ "add_settings_rule": "Sozlamalar qoidasini qoʻshish", ++ "add_transport": "Transport qoʻshish", ++ "add_transports_hint": "Autentifikatsiya maʼlumotlari, agar boʻlsa, oddiy matn sifatida saqlanishini unutmang.", ++ "additional_rows": " ta qoʻshimcha satr qoʻshildi", ++ "admin": "Administrator", ++ "admin_details": "Administrator maʼlumotlarini tahrirlash", ++ "admin_domains": "Domen tayinlashlari", ++ "admins": "Administratorlar", ++ "admins_ldap": "LDAP administratorlari", ++ "admin_quicklink": "Admin kirish sahifasiga tezkor havolani yashirish", ++ "advanced_settings": "Kengaytirilgan sozlamalar", ++ "allowed_methods": "Access-Control-Allow-Methods", ++ "allowed_origins": "Access-Control-Allow-Origin", ++ "api_allow_from": "API kirishini ushbu IP / CIDR tarmoq belgilanishlaridan ruxsat berish", ++ "api_info": "API ishlab chiqilmoqda. Hujjatlarni
/api manzilida topishingiz mumkin", ++ "api_key": "API kaliti", ++ "api_read_only": "Faqat oʻqish uchun kirish", ++ "api_read_write": "Oʻqish va yozish uchun kirish", ++ "api_skip_ip_check": "API uchun IP tekshiruvini oʻtkazib yuborish", ++ "app_hide": "Kirishda yashirish", ++ "app_links": "Ilova havolalari", ++ "app_name": "Ilova nomi", ++ "apps_name": "\"mailcow Apps\" nomi", ++ "arrival_time": "Kelish vaqti (server vaqti)", ++ "authed_user": "Avtorizatsiya qilingan foydalanuvchi", ++ "ays": "Davom etishni xohlayotganingizga ishonchingiz komilmi?", ++ "ban_list_info": "Quyida bloklangan IP roʻyxati keltirilgan: tarmoq (qolgan blok vaqti) - [amallar].
Blokdan chiqarishga navbatga qoʻyilgan IP lar bir necha soniya ichida faol bloklash roʻyxatidan olib tashlanadi.
Qizil yorliqlar qora roʻyxat orqali faol doimiy bloklarni bildiradi.", ++ "change_logo": "Logotipni oʻzgartirish", ++ "logo_normal_label": "Oddiy", ++ "logo_dark_label": "Qorongʻi rejim uchun teskari", ++ "configuration": "Konfiguratsiya", ++ "convert_html_to_text": "HTMLni oddiy matnga aylantirish", ++ "copy_to_clipboard": "Matn vaqtinchalik xotiraga koʻchirildi!", ++ "cors_settings": "CORS sozlamalari", ++ "credentials_transport_warning": "Diqqat: Yangi transport xaritasi yozuvi qoʻshish keyingi nuqta ustunlari mos keladigan barcha yozuvlar uchun maʼlumotlarni yangilaydi.", ++ "customer_id": "Mijoz ID", ++ "customize": "Sozlash", ++ "login_page": "Kirish sahifasi", ++ "destination": "Manzil", ++ "dkim_add_key": "ARC/DKIM kaliti qoʻshish", ++ "dkim_domains_selector": "Tanlovchi", ++ "dkim_domains_wo_keys": "Kalit yetishmaydigan domenlarni tanlash", ++ "dkim_from": "Kimdan", ++ "dkim_from_title": "Maʼlumotlarni koʻchirib olish uchun manba domen", ++ "dkim_key_length": "DKIM kalit uzunligi (bit)", ++ "dkim_key_missing": "Kalit yetishmaydi", ++ "dkim_key_unused": "Kalit ishlatilmagan", ++ "dkim_key_valid": "Kalit haqiqiy", ++ "dkim_keys": "ARC/DKIM kalitlari", ++ "dkim_overwrite_key": "Mavjud DKIM kalitini ustidan yozish", ++ "dkim_private_key": "Maxfiy kalit", ++ "dkim_to": "Kimga", ++ "dkim_to_title": "Maqsad domen(lar) — ustidan yoziladi", ++ "domain": "Domen", ++ "domain_admin": "Domen administratori", ++ "domain_admins": "Domen administratorlari", ++ "domainadmin_quicklink": "Domen admin kirish sahifasiga tezkor havolani yashirish", ++ "domain_s": "Domen(lar)", ++ "duplicate": "Nusxalash", ++ "duplicate_dkim": "DKIM yozuvini nusxalash", ++ "edit": "Tahrirlash", ++ "empty": "Natijalar yoʻq", ++ "excludes": "Ushbu qabul qiluvchilarni istisno qiladi", ++ "f2b_ban_time": "Bloklash vaqti (s)", ++ "f2b_ban_time_increment": "Har bir bloklashda blok vaqti ortadi", ++ "f2b_blacklist": "Qora roʻyxatdagi tarmoqlar/xostlar", ++ "f2b_filter": "Regex filtrlari", ++ "f2b_list_info": "Qora roʻyxatdagi xost yoki tarmoq har doim oq roʻyxat elementidan ustun keladi. Roʻyxat yangilanishlarini qoʻllash uchun bir necha soniya kerak boʻladi.", ++ "f2b_manage_external": "Fail2ban ni tashqi boshqarish", ++ "f2b_manage_external_info": "Fail2ban hali ham banlist ni saqlaydi, ammo trafikni bloklash uchun faol qoidalarni oʻrnatmaydi. Trafikni tashqi tomondan bloklash uchun quyida yaratilgan banlist dan foydalaning.", ++ "f2b_max_attempts": "Maks. urinishlar", ++ "f2b_max_ban_time": "Maks. bloklash vaqti (s)", ++ "f2b_netban_ipv4": "Blokni qoʻllash uchun IPv4 subtarmoq oʻlchami (8-32)", ++ "f2b_netban_ipv6": "Blokni qoʻllash uchun IPv6 subtarmoq oʻlchami (8-128)", ++ "f2b_parameters": "Fail2ban parametrlari", ++ "f2b_regex_info": "Eʼtiborga olinadigan jurnallar: SOGo, Postfix, Dovecot, PHP-FPM.", ++ "f2b_retry_window": "Maks. urinishlar uchun qayta urinish oynasi (s)", ++ "f2b_whitelist": "Oq roʻyxatdagi tarmoqlar/xostlar", ++ "filter": "Filtr", ++ "filter_table": "Filtr jadvali", ++ "force_sso_text": "Tashqi OIDC provayder sozlangan boʻlsa, bu variant standart mailcow kirish formalarini yashiradi va faqat Yagona kirish tugmasini koʻrsatadi", ++ "force_sso": "mailcow kirishini oʻchirib, faqat Yagona kirishni koʻrsatish", ++ "forwarding_hosts": "Yoʻnaltirish xostlari", ++ "forwarding_hosts_add_hint": "Siz IPv4/IPv6 manzillarini, CIDR yozuvidagi tarmoqlarni, xost nomlarini (IP manzillariga aylantiriladi) yoki domen nomlarini (SPF TXT yoki yoʻq boʻlsa MX yozuvlarini soʻrash orqali IP manzillariga aylantiriladi) belgilashingiz mumkin.", ++ "forwarding_hosts_hint": "Kiruvchi xabarlar bu yerda keltirilgan istalgan xostlardan shartsiz qabul qilinadi. Bu xostlar keyin DNSBL ga qarshi tekshirilmaydi yoki greylisting ga olinmaydi. Ulardan kelgan spam hech qachon rad etilmaydi, ammo ixtiyoriy ravishda Junk papkasiga joylashtirilishi mumkin. Buning eng keng tarqalgan ishlatilishi — mailcow serveringizga kiruvchi xatlarni yoʻnaltirish qoidasi oʻrnatilgan pochta serverlarini koʻrsatish.", ++ "from": "Kimdan", ++ "generate": "yaratish", ++ "guid": "GUID - noyob nusxa ID si", ++ "guid_and_license": "GUID va litsenziya", ++ "hash_remove_info": "Ratelimit hashini oʻchirish (agar mavjud boʻlsa) uning hisoblagichini butunlay tiklaydi.
\r\n Har bir hash alohida rang bilan koʻrsatiladi.", ++ "help_text": "Kirish maskasi ostidagi yordam matnini bekor qilish (HTML ruxsat etilgan)", ++ "host": "Xost", ++ "html": "HTML", ++ "iam": "Identifikatsiya provayderi", ++ "iam_attribute_field": "Atribut maydoni", ++ "iam_authorize_url": "Avtorizatsiya nuqtasi", ++ "iam_auth_flow": "Autentifikatsiya oqimi", ++ "iam_auth_flow_info": "Yagona kirish (SSO) uchun ishlatiladigan Authorization Code Flow (Keycloak da Standard Flow) qoʻshimcha ravishda, mailcow toʻgʻridan-toʻgʻri maʼlumotlar bilan Autentifikatsiya oqimini ham qoʻllab-quvvatlaydi. Mailpassword Flow Keycloak Admin REST API yordamida foydalanuvchi maʼlumotlarini tekshirishga harakat qiladi. mailcow Keycloakda xaritalangan mailcow_password atributidan xeshlangan parolni oladi.", ++ "iam_basedn": "Base DN", ++ "iam_client_id": "Mijoz ID", ++ "iam_client_secret": "Mijoz maxfiy soʻzi", ++ "iam_client_scopes": "Mijoz qamrovlari", ++ "iam_default_template": "Standart shablon", ++ "iam_default_template_description": "Agar foydalanuvchiga shablon tayinlanmagan boʻlsa, pochta qutisini yaratishda standart shablon ishlatiladi, lekin pochta qutisini yangilash uchun emas.", ++ "iam_description": "Autentifikatsiya uchun tashqi provayderni sozlash
Foydalanuvchi pochta qutilari atribut xaritalashi oʻrnatilgan boʻlsa, ular birinchi marta kirgan zahoti avtomatik yaratiladi.", ++ "iam_extra_permission": "Quyidagi sozlamalarning ishlashi uchun Keycloak dagi mailcow mijoziga Service account va view-users ruxsati kerak.", ++ "iam_host": "Xost", ++ "iam_host_info": "Bir yoki bir nechta LDAP xostni vergul bilan ajratib kiriting.", ++ "iam_import_users": "Foydalanuvchilarni import qilish", ++ "iam_login_provisioning": "Kirishda foydalanuvchilarni avto-yaratish", ++ "iam_mapping": "Atribut xaritalashi", ++ "iam_bindpass": "Bind paroli", ++ "iam_periodic_full_sync": "Davriy toʻliq sinxronizatsiya", ++ "iam_port": "Port", ++ "iam_realm": "Realm", ++ "iam_redirect_url": "Yoʻnaltirish URL", ++ "iam_rest_flow": "Mailpassword Flow", ++ "iam_server_url": "Server URL", ++ "iam_sso": "Yagona kirish (SSO)", ++ "iam_sync_interval": "Sinxronizatsiya / import oraligʻi (daqiqa)", ++ "iam_test_connection": "Ulanishni tekshirish", ++ "iam_token_url": "Token nuqtasi", ++ "iam_userinfo_url": "Foydalanuvchi maʼlumotlari nuqtasi", ++ "iam_username_field": "Foydalanuvchi nomi maydoni", ++ "iam_binddn": "Bind DN", ++ "iam_use_ssl": "SSL dan foydalanish", ++ "iam_use_ssl_info": "SSL yoqilsa va port 389 ga oʻrnatilgan boʻlsa, u avtomatik ravishda 636 ga oʻzgartiriladi.", ++ "iam_use_tls": "StartTLS dan foydalanish", ++ "iam_use_tls_info": "TLS yoqilsa, LDAP serveringiz uchun standart portni (389) ishlatishingiz kerak. SSL portlari ishlatilmaydi.", ++ "iam_version": "Versiya", ++ "ignore_ssl_error": "SSL xatolarini eʼtiborsiz qoldirish", ++ "import": "Import", ++ "import_private_key": "Maxfiy kalitni import qilish", ++ "in_use_by": "Kim ishlatadi", ++ "inactive": "Nofaol", ++ "include_exclude": "Kiritish/Istisno qilish", ++ "include_exclude_info": "Standart holatda — tanlovsiz — barcha pochta qutilariga murojaat qilinadi", ++ "includes": "Ushbu qabul qiluvchilarni kiritish", ++ "ip_check": "IP tekshiruvi", ++ "ip_check_disabled": "IP tekshiruvi oʻchirilgan. Uni quyidagi joydan yoqishingiz mumkin:
Tizim > Konfiguratsiya > Variantlar > Sozlash", ++ "ip_check_opt_in": "Tashqi IP manzillarni aniqlash uchun ipv4.mailcow.email va ipv6.mailcow.email uchinchi tomon xizmatidan foydalanishga rozilik.", ++ "is_mx_based": "MX asosida", ++ "last_applied": "Oxirgi qoʻllanilgan", ++ "license_info": "Litsenziya talab qilinmaydi, ammo bu loyihaning rivojlanishiga yordam beradi.
GUID ni bu yerda roʻyxatdan oʻtkazing yoki mailcow oʻrnatmangiz uchun yordam sotib oling.", ++ "link": "Havola", ++ "loading": "Iltimos, kuting...", ++ "login_time": "Kirish vaqti", ++ "logo_info": "Tasviringiz yuqori navigatsiya paneli uchun 40px balandlikka, bosh sahifa uchun maks. 250px kenglikka oʻlchanadi. Masshtablanadigan grafika tavsiya etiladi.", ++ "lookup_mx": "Manzil — MX nomiga mos keladigan muntazam ifoda (.*\\.google\\.com — google.com bilan tugaydigan MX ga yoʻnaltirilgan barcha pochtani ushbu nuqta orqali yoʻnaltirish uchun)", ++ "main_name": "\"mailcow UI\" nomi", ++ "merged_vars_hint": "Kulrang satrlar vars.(local.)inc.php dan birlashtirilgan va oʻzgartirib boʻlmaydi.", ++ "message": "Xabar", ++ "message_size": "Xabar oʻlchami", ++ "nexthop": "Keyingi nuqta", ++ "needs_restart": "qayta ishga tushirish kerak", ++ "no": "✕", ++ "no_active_bans": "Faol bloklar yoʻq", ++ "no_new_rows": "Boshqa satrlar mavjud emas", ++ "no_record": "Yozuv yoʻq", ++ "oauth2_apps": "OAuth2 ilovalari", ++ "oauth2_add_client": "OAuth2 mijozini qoʻshish", ++ "oauth2_client_id": "Mijoz ID", ++ "oauth2_client_secret": "Mijoz maxfiy soʻzi", ++ "oauth2_info": "OAuth2 amalga oshirilishi \"Authorization Code\" grant turini qoʻllab-quvvatlaydi va refresh tokenlarini chiqaradi.
\r\nServer shuningdek refresh token ishlatilgandan keyin avtomatik ravishda yangi refresh tokenlarini chiqaradi.

\r\n• Standart qamrov — profile. Faqat pochta qutisi foydalanuvchilari OAuth2 ga qarshi autentifikatsiya qilinishi mumkin. Agar scope parametri tashlab ketilgan boʻlsa, u profile ga qaytadi.
\r\n• state parametri mijoz tomonidan avtorizatsiya soʻrovining bir qismi sifatida yuborilishi shart.

\r\nOAuth2 API ga soʻrovlar uchun yoʻllar:
\r\n
    \r\n
  • Avtorizatsiya nuqtasi: /oauth/authorize
  • \r\n
  • Token nuqtasi: /oauth/token
  • \r\n
  • Resurs sahifasi: /oauth/profile
  • \r\n
\r\nMijoz maxfiy soʻzini qayta yaratish mavjud avtorizatsiya kodlarini muddati tugashiga olib kelmaydi, lekin ular tokenni yangilashda muvaffaqiyatsiz boʻladi.

\r\nMijoz tokenlarini bekor qilish barcha faol sessiyalarning darhol tugashiga olib keladi. Barcha mijozlar qayta autentifikatsiya qilishlari kerak.", ++ "oauth2_redirect_uri": "Yoʻnaltirish URI", ++ "oauth2_renew_secret": "Yangi mijoz maxfiy soʻzini yaratish", ++ "oauth2_revoke_tokens": "Barcha mijoz tokenlarini bekor qilish", ++ "optional": "ixtiyoriy", ++ "options": "Variantlar", ++ "password": "Parol", ++ "password_length": "Parol uzunligi", ++ "password_policy": "Parol siyosati", ++ "password_policy_chars": "Kamida bitta alifbo belgisini oʻz ichiga olishi kerak", ++ "password_policy_length": "Minimal parol uzunligi %d", ++ "password_policy_lowerupper": "Kichik va katta harflarni oʻz ichiga olishi kerak", ++ "password_policy_numbers": "Kamida bitta raqamni oʻz ichiga olishi kerak", ++ "password_policy_special_chars": "Maxsus belgilarni oʻz ichiga olishi kerak", ++ "password_repeat": "Tasdiqlash paroli (takrorlang)", ++ "password_reset_info": "Agar tiklash uchun e-pochta kiritilmagan boʻlsa, bu funksiyadan foydalanib boʻlmaydi.", ++ "password_reset_settings": "Parolni tiklash sozlamalari", ++ "password_reset_tmpl_html": "HTML shablon", ++ "password_reset_tmpl_text": "Matnli shablon", ++ "password_settings": "Parol sozlamalari", ++ "priority": "Muhimlik darajasi", ++ "private_key": "Maxfiy kalit", ++ "quarantine": "Karantin", ++ "quarantine_bcc": "Barcha bildirishnomalarning nusxasini (BCC) ushbu qabul qiluvchiga yuborish:
Oʻchirish uchun boʻsh qoldiring. Imzolanmagan, tekshirilmagan xat. Faqat ichki yetkazib berilishi kerak.", ++ "quarantine_exclude_domains": "Domenlar va taxallus domenlarini istisno qilish", ++ "quarantine_max_age": "Maksimal yosh (kunlarda)
Qiymat 1 kun yoki undan koʻp boʻlishi kerak.", ++ "quarantine_max_score": "Agar xatning spam bahosi ushbu qiymatdan yuqori boʻlsa, bildirishnomani rad etish:
Standart 9999.0", ++ "quarantine_max_size": "Maksimal oʻlcham (MiB) (kattaroq elementlar rad etiladi):
0 cheksizlikni bildirmaydi.", ++ "quarantine_notification_html": "Bildirishnoma e-pochta shabloni:
Standart shablonni tiklash uchun boʻsh qoldiring.", ++ "quarantine_notification_sender": "Bildirishnoma e-pochta joʻnatuvchisi", ++ "quarantine_notification_subject": "Bildirishnoma e-pochta mavzusi", ++ "quarantine_redirect": "Barcha bildirishnomalarni ushbu qabul qiluvchiga yoʻnaltirish:
Oʻchirish uchun boʻsh qoldiring. Imzolanmagan, tekshirilmagan xat. Faqat ichki yetkazib berilishi kerak.", ++ "quarantine_release_format": "Chiqarilgan elementlar formati", ++ "quarantine_release_format_att": "Ilova sifatida", ++ "quarantine_release_format_raw": "Oʻzgartirilmagan asl nusxa", ++ "quarantine_retention_size": "Pochta qutisi uchun saqlash:
0 — nofaolligini bildiradi.", ++ "quicklink_text": "Boshqa kirish sahifalariga tezkor havolalarni kirish formasi ostida koʻrsatish yoki yashirish", ++ "quota_notification_html": "Bildirishnoma e-pochta shabloni:
Standart shablonni tiklash uchun boʻsh qoldiring.", ++ "quota_notification_sender": "Bildirishnoma e-pochta joʻnatuvchisi", ++ "quota_notification_subject": "Bildirishnoma e-pochta mavzusi", ++ "quota_notifications": "Kvota bildirishnomalari", ++ "quota_notifications_info": "Kvota bildirishnomalari foydalanuvchilarga foydalanish 80% va 95% ga yetganda bir martadan yuboriladi.", ++ "quota_notifications_vars": "{{percent}} — foydalanuvchining joriy kvotasi
{{username}} — pochta qutisi nomi", ++ "queue_unban": "blokdan chiqarish", ++ "r_active": "Faol cheklovlar", ++ "r_inactive": "Nofaol cheklovlar", ++ "r_info": "Faol cheklovlar roʻyxatidagi kulrang/oʻchirilgan elementlar mailcow uchun haqiqiy cheklovlar sifatida tanilmaydi va koʻchirib boʻlmaydi. Nomaʼlum cheklovlar baribir koʻrinish tartibida oʻrnatiladi.
inc/vars.local.inc.php da yangi elementlarni qoʻshib, ularni almashtirishingiz mumkin.", ++ "rate_name": "Tezlik nomi", ++ "recipients": "Qabul qiluvchilar", ++ "refresh": "Yangilash", ++ "regen_api_key": "API kalitini qayta yaratish", ++ "regex_maps": "Regex xaritalari", ++ "relay_from": "\"From:\" manzili", ++ "relay_rcpt": "\"To:\" manzili", ++ "relay_run": "Sinovni ishga tushirish", ++ "relayhosts": "Joʻnatuvchiga bogʻliq transportlar", ++ "relayhosts_hint": "Domen konfiguratsiya muloqotida tanlash mumkin boʻlgan joʻnatuvchiga bogʻliq transportlarni belgilang.
\r\n Transport xizmati har doim \"smtp:\" va shuning uchun taklif qilinganda TLS ga harakat qiladi. Oʻralgan TLS (SMTPS) qoʻllab-quvvatlanmaydi. Foydalanuvchining individual chiquvchi TLS siyosati sozlamasi eʼtiborga olinadi.
\r\n Taxallus domenlari bilan birga tanlangan domenlarga taʼsir qiladi.", ++ "remove": "Olib tashlash", ++ "remove_row": "Satrni olib tashlash", ++ "reset_default": "Standartga qaytarish", ++ "reset_limit": "Hash ni olib tashlash", ++ "reset_password_vars": "{{link}} Yaratilgan parolni tiklash havolasi
{{username}} Parolni tiklashni soʻragan foydalanuvchining pochta qutisi nomi
{{username2}} Tiklash uchun pochta qutisi nomi
{{date}} Parolni tiklash soʻrovi qilingan sana
{{token_lifetime}} Daqiqalardagi token muddati
{{hostname}} mailcow xost nomi", ++ "restore_template": "Standart shablonni tiklash uchun boʻsh qoldiring.", ++ "routing": "Yoʻnaltirish", ++ "rsetting_add_rule": "Qoida qoʻshish", ++ "rsetting_content": "Qoida mazmuni", ++ "rsetting_desc": "Qisqa tavsif", ++ "rsetting_no_selection": "Iltimos, qoidani tanlang", ++ "rsetting_none": "Qoidalar mavjud emas", ++ "rsettings_insert_preset": "Misol presetini kiritish \"%s\"", ++ "rsettings_preset_1": "Autentifikatsiya qilingan foydalanuvchilar uchun DKIM va tezlik chegarasidan boshqa hamma narsani oʻchirib qoʻyish", ++ "rsettings_preset_2": "Postmasterlar spamni xohlaydi", ++ "rsettings_preset_3": "Pochta qutisi uchun faqat maxsus joʻnatuvchilarga ruxsat berish (yaʼni, faqat ichki pochta qutisi sifatida ishlatish)", ++ "rsettings_preset_4": "Domen uchun Rspamd ni oʻchirish", ++ "rspamd_com_settings": "Sozlama nomi avtomatik yaratiladi, quyidagi misol presetlariga qarang. Batafsil maʼlumot uchun Rspamd hujjatlariga qarang", ++ "rspamd_global_filters": "Global filtr xaritalari", ++ "rspamd_global_filters_agree": "Ehtiyot boʻlaman!", ++ "rspamd_global_filters_info": "Global filtr xaritalari turli xil global rad etish va ruxsat berish roʻyxatlarini oʻz ichiga oladi.", ++ "rspamd_global_filters_regex": "Ularning nomlari ularning maqsadini tushuntiradi. Barcha mazmun \"/pattern/options\" formatidagi haqiqiy muntazam ifodalarni oʻz ichiga olishi kerak (masalan, /.+@domain\\.tld/i).
\r\n Har bir regex satriga oddiy tekshiruvlar bajariladi, ammo agar Rspamd sintaksisni toʻgʻri oʻqiy olmasa, uning funksionalligi buzilishi mumkin.
\r\n Rspamd oʻzgarganda xarita mazmunini oʻqishga harakat qiladi. Agar muammolarga duch kelsangiz, xarita qayta yuklanishi uchun Rspamd ni qayta ishga tushiring.
Qora roʻyxatdagi elementlar karantindan istisno qilinadi.", ++ "rspamd_settings_map": "Rspamd sozlamalar xaritasi", ++ "sal_level": "Moo darajasi", ++ "save": "Oʻzgarishlarni saqlash", ++ "search_domain_da": "Domenlarni qidirish", ++ "send": "Joʻnatish", ++ "sender": "Joʻnatuvchi", ++ "service": "Xizmat", ++ "service_id": "Xizmat ID", ++ "source": "Manba", ++ "spamfilter": "Spam filtri", ++ "subject": "Mavzu", ++ "success": "Muvaffaqiyatli", ++ "sys_mails": "Tizim xatlari", ++ "task": "Vazifa", ++ "text": "Matn", ++ "time": "Vaqt", ++ "title": "Sarlavha", ++ "title_name": "\"mailcow UI\" veb-sayt sarlavhasi", ++ "to_top": "Yuqoriga qaytish", ++ "transport_dest_format": "Regex yoki sintaksis: example.org, .example.org, *, box@example.org (bir nechta qiymatlarni vergul bilan ajratish mumkin)", ++ "transport_maps": "Transport xaritalari", ++ "transport_test_rcpt_info": "• Tashqi manzilga relay qilishni sinash uchun null@hosted.mailcow.de dan foydalaning.", ++ "transports_hint": "• Transport xaritasi yozuvi joʻnatuvchiga bogʻliq transport xaritasidan ustun.
\r\n• MX asosidagi transportlar afzalroq ishlatiladi.
\r\n• Foydalanuvchi boʻyicha chiquvchi TLS siyosati sozlamalari eʼtiborga olinmaydi va faqat TLS siyosati xaritasi yozuvlari orqali majburlanishi mumkin.
\r\n• Belgilangan transportlar uchun transport xizmati har doim \"smtp:\" va shuning uchun taklif qilinganda TLS ga harakat qiladi. Oʻralgan TLS (SMTPS) qoʻllab-quvvatlanmaydi.
\r\n• \"/localhost$/\" ga mos keladigan manzillar har doim \"local:\" orqali tashiladi, shuning uchun \"*\" manzili bu manzillarga qoʻllanmaydi.
\r\n• Misol uchun keyingi nuqta \"[host]:25\" uchun maʼlumotlarni aniqlash uchun, Postfix har doim \"[host]:25\" ni qidirishdan oldin \"host\" ni soʻraydi. Bu xatti-harakat \"host\" va \"[host]:25\" ni bir vaqtning oʻzida ishlatishni imkonsiz qiladi.", ++ "ui_footer": "Pastki qism (HTML ruxsat etilgan)", ++ "ui_header_announcement": "Eʼlonlar", ++ "ui_header_announcement_active": "Eʼlonni faollashtirish", ++ "ui_header_announcement_content": "Matn (HTML ruxsat etilgan)", ++ "ui_header_announcement_help": "Eʼlon barcha tizimga kirgan foydalanuvchilarga va UI ning kirish ekranida koʻrinadi.", ++ "ui_header_announcement_select": "Eʼlon turini tanlang", ++ "ui_header_announcement_type": "Tur", ++ "ui_header_announcement_type_danger": "Juda muhim", ++ "ui_header_announcement_type_info": "Maʼlumot", ++ "ui_header_announcement_type_warning": "Muhim", ++ "ui_texts": "UI yorliqlari va matnlari", ++ "unban_pending": "blokdan chiqarish kutilmoqda", ++ "unchanged_if_empty": "Oʻzgartirilmagan boʻlsa, boʻsh qoldiring", ++ "upload": "Yuklash", ++ "username": "Foydalanuvchi nomi", ++ "user_link": "Foydalanuvchi havolasi", ++ "user_quicklink": "Foydalanuvchi kirish sahifasiga tezkor havolani yashirish", ++ "validate_license_now": "GUID ni litsenziya serveriga qarshi tekshirish", ++ "verify": "Tasdiqlash", ++ "yes": "✓" ++ }, ++ "danger": { ++ "access_denied": "Kirish rad etildi yoki noma'lum forma ma'lumotlari", ++ "tfa_removal_blocked": "Ikki faktorli autentifikatsiyani olib tashlab boʻlmaydi, chunki u sizning hisobingiz uchun talab qilinadi.", ++ "alias_domain_invalid": "%s taxallus domeni noto'g'ri", ++ "alias_empty": "Taxallus manzili boʻsh boʻlmasligi kerak", ++ "alias_goto_identical": "Taxallus va yoʻnaltirish manzili bir xil boʻlmasligi kerak", ++ "alias_invalid": "%s taxallus manzili noto'g'ri", ++ "aliasd_targetd_identical": "Taxallus domeni maqsad domeniga teng boʻlmasligi kerak: %s", ++ "aliases_in_use": "Maks. taxalluslar %d dan katta yoki teng boʻlishi kerak", ++ "app_name_empty": "Ilova nomi boʻsh boʻlolmaydi", ++ "app_passwd_id_invalid": "Ilova paroli ID %s noto'g'ri", ++ "authsource_in_use": "Identifikatsiya provayderini oʻzgartirib yoki oʻchirib boʻlmaydi, chunki u hozirda bir yoki bir nechta foydalanuvchilar tomonidan ishlatilmoqda.", ++ "bcc_empty": "BCC manzili boʻsh boʻlolmaydi", ++ "bcc_exists": "%s turi uchun %s BCC xaritasi mavjud", ++ "bcc_must_be_email": "BCC manzili %s haqiqiy e-pochta manzili emas", ++ "comment_too_long": "Izoh juda uzun, maks. 160 ta belgiga ruxsat berilgan", ++ "cors_invalid_method": "Noto'g'ri Allow-Method belgilangan", ++ "cors_invalid_origin": "Noto'g'ri Allow-Origin belgilangan", ++ "defquota_empty": "Bitta pochta qutisi uchun standart kvota 0 boʻlmasligi kerak.", ++ "demo_mode_enabled": "Demo rejim yoqilgan", ++ "description_invalid": "%s uchun resurs tavsifi noto'g'ri", ++ "dkim_domain_or_sel_exists": "\"%s\" uchun DKIM kaliti mavjud va u ustidan yozilmaydi", ++ "dkim_domain_or_sel_invalid": "DKIM domeni yoki tanlovchi noto'g'ri: %s", ++ "domain_cannot_match_hostname": "Domen xost nomiga mos kelishi mumkin emas", ++ "domain_exists": "%s domeni allaqachon mavjud", ++ "domain_invalid": "Domen nomi boʻsh yoki noto'g'ri", ++ "domain_not_empty": "Boʻsh boʻlmagan %s domenini olib tashlab boʻlmaydi", ++ "domain_not_found": "%s domeni topilmadi", ++ "domain_quota_m_in_use": "Domen kvotasi %s MiB dan katta yoki teng boʻlishi kerak", ++ "extended_sender_acl_denied": "Tashqi joʻnatuvchi manzillarini oʻrnatish uchun ACL yetishmayapti", ++ "extra_acl_invalid": "Tashqi joʻnatuvchi manzili \"%s\" noto'g'ri", ++ "extra_acl_invalid_domain": "Tashqi joʻnatuvchi \"%s\" noto'g'ri domendan foydalanmoqda", ++ "fido2_verification_failed": "FIDO2 tekshiruvi muvaffaqiyatsiz: %s", ++ "file_open_error": "Faylni yozish uchun ochib boʻlmadi", ++ "filter_type": "Notoʻgʻri filtr turi", ++ "from_invalid": "Joʻnatuvchi boʻsh boʻlmasligi kerak", ++ "generic_server_error": "Kutilmagan server xatosi yuz berdi. Iltimos, administratoringiz bilan bogʻlaning.", ++ "global_filter_write_error": "Filtr faylini yozib boʻlmadi: %s", ++ "global_map_invalid": "Global xarita ID %s noto'g'ri", ++ "global_map_write_error": "Global xarita ID %s ni yozib boʻlmadi: %s", ++ "goto_empty": "Taxallus manzili kamida bitta haqiqiy yoʻnaltirish manzilini oʻz ichiga olishi kerak", ++ "goto_invalid": "Yoʻnaltirish manzili %s noto'g'ri", ++ "ham_learn_error": "Ham oʻrgatish xatosi: %s", ++ "iam_test_connection": "Ulanish muvaffaqiyatsiz", ++ "imagick_exception": "Xato: Tasvirni oʻqishda Imagick istisnosi", ++ "img_dimensions_exceeded": "Tasvir maksimal tasvir oʻlchamidan oshib ketdi", ++ "img_invalid": "Tasvir faylini tekshirib boʻlmadi", ++ "img_size_exceeded": "Tasvir maksimal fayl oʻlchamidan oshib ketdi", ++ "img_tmp_missing": "Tasvir faylini tekshirib boʻlmadi: Vaqtinchalik fayl topilmadi", ++ "invalid_bcc_map_type": "Noto'g'ri BCC xarita turi", ++ "invalid_destination": "Manzil formati \"%s\" noto'g'ri", ++ "invalid_filter_type": "Noto'g'ri filtr turi", ++ "invalid_host": "Noto'g'ri xost belgilangan: %s", ++ "invalid_mime_type": "Noto'g'ri MIME turi", ++ "invalid_nexthop": "Keyingi nuqta formati noto'g'ri", ++ "invalid_nexthop_authenticated": "Keyingi nuqta boshqa maʼlumotlar bilan mavjud, iltimos avval bu keyingi nuqta uchun mavjud maʼlumotlarni yangilang.", ++ "invalid_recipient_map_new": "Yangi qabul qiluvchi noto'g'ri belgilangan: %s", ++ "invalid_recipient_map_old": "Asl qabul qiluvchi noto'g'ri belgilangan: %s", ++ "invalid_reset_token": "Noto'g'ri tiklash tokeni", ++ "ip_list_empty": "Ruxsat etilgan IP roʻyxati boʻsh boʻlolmaydi", ++ "is_alias": "%s allaqachon taxallus manzili sifatida tanilgan", ++ "is_alias_or_mailbox": "%s allaqachon taxallus, pochta qutisi yoki taxallus domenidan kengaytirilgan taxallus manzili sifatida tanilgan.", ++ "is_spam_alias": "%s allaqachon vaqtinchalik taxallus manzili (spam taxallus manzili) sifatida tanilgan", ++ "last_key": "Oxirgi kalitni oʻchirib boʻlmaydi, iltimos uning oʻrniga TFA ni oʻchiring.", ++ "login_failed": "Kirish muvaffaqiyatsiz", ++ "mailbox_defquota_exceeds_mailbox_maxquota": "Standart kvota maksimal kvota chegarasidan oshib ketdi", ++ "mailbox_invalid": "Pochta qutisi nomi noto'g'ri", ++ "mailbox_quota_exceeded": "Kvota domen chegarasidan oshib ketdi (maks. %d MiB)", ++ "mailbox_quota_exceeds_domain_quota": "Maks. kvota domen kvota chegarasidan oshib ketdi", ++ "mailbox_quota_left_exceeded": "Yetarli joy qolmadi (qolgan joy: %d MiB)", ++ "mailboxes_in_use": "Maks. pochta qutilari %d dan katta yoki teng boʻlishi kerak", ++ "malformed_username": "Noto'g'ri shakldagi foydalanuvchi nomi", ++ "map_content_empty": "Xarita mazmuni boʻsh boʻlolmaydi", ++ "max_age_invalid": "Maks. yosh %s noto'g'ri", ++ "max_alias_exceeded": "Maks. taxalluslar oshib ketdi", ++ "max_mailbox_exceeded": "Maks. pochta qutilari oshib ketdi (%d / %d)", ++ "max_quota_in_use": "Pochta qutisi kvotasi %d MiB dan katta yoki teng boʻlishi kerak", ++ "maxquota_empty": "Bitta pochta qutisi uchun maks. kvota 0 boʻlmasligi kerak.", ++ "mode_invalid": "Rejim %s noto'g'ri", ++ "mx_invalid": "MX yozuvi %s noto'g'ri", ++ "mysql_error": "MySQL xatosi: %s", ++ "network_host_invalid": "Noto'g'ri tarmoq yoki xost: %s", ++ "next_hop_interferes": "%s keyingi nuqta %s bilan tortishuvga kirishadi", ++ "next_hop_interferes_any": "Mavjud keyingi nuqta %s bilan tortishuvga kirishadi", ++ "nginx_reload_failed": "Nginx qayta yuklash muvaffaqiyatsiz: %s", ++ "no_user_defined": "Foydalanuvchi belgilanmagan", ++ "object_exists": "%s obyekti allaqachon mavjud", ++ "object_is_not_numeric": "%s qiymati raqamli emas", ++ "password_complexity": "Parol siyosatga mos kelmaydi", ++ "password_empty": "Parol boʻsh boʻlmasligi kerak", ++ "password_mismatch": "Tasdiqlash paroli mos kelmadi", ++ "password_reset_invalid_user": "Pochta qutisi topilmadi yoki tiklash uchun e-pochta oʻrnatilmagan", ++ "password_reset_na": "Parolni tiklash hozirda mavjud emas. Iltimos, administratoringiz bilan bogʻlaning.", ++ "policy_list_from_exists": "Berilgan nomli yozuv mavjud", ++ "policy_list_from_invalid": "Yozuv noto'g'ri formatga ega", ++ "private_key_error": "Maxfiy kalit xatosi: %s", ++ "pushover_credentials_missing": "Pushover tokeni va/yoki kaliti yetishmayapti", ++ "pushover_key": "Pushover kaliti notoʻgʻri formatga ega", ++ "pushover_token": "Pushover tokeni notoʻgʻri formatga ega", ++ "quarantine_category_invalid": "Karantin turkumi quyidagilardan biri boʻlishi kerak: add_header, reject, all", ++ "quota_not_0_not_numeric": "Kvota raqamli va >= 0 boʻlishi kerak", ++ "recipient_map_entry_exists": "Qabul qiluvchi xaritasi yozuvi \"%s\" mavjud", ++ "recovery_email_failed": "Tiklash e-pochtasini yuborib boʻlmadi. Iltimos, administratoringiz bilan bogʻlaning.", ++ "redis_error": "Redis xatosi: %s", ++ "relayhost_invalid": "Xarita yozuvi %s noto'g'ri", ++ "release_send_failed": "Xabarni chiqarib boʻlmadi: %s", ++ "required_data_missing": "Talab qilinadigan ma'lumotlar %s yetishmayapti", ++ "reset_f2b_regex": "Regex filtrini oʻz vaqtida tiklab boʻlmadi, iltimos qaytadan urinib koʻring yoki bir necha soniya kuting va sahifani qayta yuklang.", ++ "reset_token_limit_exceeded": "Tiklash tokeni chegarasi oshib ketdi. Iltimos, keyinroq urinib koʻring.", ++ "resource_invalid": "Resurs nomi %s noto'g'ri", ++ "rl_timeframe": "Tezlik chegarasi vaqt oraligʻi noto'g'ri", ++ "rspamd_ui_pw_length": "Rspamd UI paroli kamida 6 ta belgi uzunlikda boʻlishi kerak", ++ "script_empty": "Skript boʻsh boʻlolmaydi", ++ "sender_acl_invalid": "Joʻnatuvchi ACL qiymati %s noto'g'ri", ++ "set_acl_failed": "ACL ni oʻrnatib boʻlmadi", ++ "settings_map_invalid": "Sozlamalar xaritasi ID %s noto'g'ri", ++ "sieve_error": "Sieve tahlilchisi xatosi: %s", ++ "spam_learn_error": "Spam oʻrgatish xatosi: %s", ++ "subject_empty": "Mavzu boʻsh boʻlmasligi kerak", ++ "target_domain_invalid": "Maqsad domen %s noto'g'ri", ++ "targetd_not_found": "Maqsad domen %s topilmadi", ++ "targetd_relay_domain": "Maqsad domen %s relay domen", ++ "template_exists": "%s shabloni allaqachon mavjud", ++ "template_id_invalid": "Shablon ID %s noto'g'ri", ++ "template_name_invalid": "Shablon nomi noto'g'ri", ++ "temp_error": "Vaqtinchalik xato", ++ "text_empty": "Matn boʻsh boʻlmasligi kerak", ++ "tfa_token_invalid": "TFA tokeni noto'g'ri", ++ "tls_policy_map_dest_invalid": "Siyosat manzili noto'g'ri", ++ "tls_policy_map_entry_exists": "TLS siyosati xaritasi yozuvi \"%s\" mavjud", ++ "tls_policy_map_parameter_invalid": "Siyosat parametri noto'g'ri", ++ "to_invalid": "Qabul qiluvchi boʻsh boʻlmasligi kerak", ++ "totp_verification_failed": "TOTP tekshiruvi muvaffaqiyatsiz", ++ "transport_dest_exists": "Transport manzili \"%s\" mavjud", ++ "webauthn_verification_failed": "WebAuthn tekshiruvi muvaffaqiyatsiz: %s", ++ "webauthn_authenticator_failed": "Tanlangan autentifikator topilmadi", ++ "webauthn_publickey_failed": "Tanlangan autentifikator uchun ochiq kalit saqlanmagan", ++ "webauthn_username_failed": "Tanlangan autentifikator boshqa hisobga tegishli", ++ "unknown": "Noma'lum xato yuz berdi", ++ "unknown_tfa_method": "Noma'lum TFA usuli", ++ "unlimited_quota_acl": "Cheksiz kvota ACL tomonidan taqiqlangan", ++ "username_invalid": "Foydalanuvchi nomi %s ishlatib boʻlmaydi", ++ "validity_missing": "Iltimos, amal qilish muddatini tayinlang", ++ "value_missing": "Iltimos, barcha qiymatlarni kiriting", ++ "version_invalid": "Versiya %s noto'g'ri", ++ "yotp_verification_failed": "Yubico OTP tekshiruvi muvaffaqiyatsiz: %s" ++ }, ++ "datatables": { ++ "collapse_all": "Hammasini yigʻish", ++ "decimal": ".", ++ "emptyTable": "Jadvalda ma'lumot mavjud emas", ++ "expand_all": "Hammasini kengaytirish", ++ "info": "_TOTAL_ tadan _START_ dan _END_ gacha koʻrsatilmoqda", ++ "infoEmpty": "0 tadan 0 dan 0 gacha koʻrsatilmoqda", ++ "infoFiltered": "(jami _MAX_ tadan filtrlangan)", ++ "infoPostFix": "", ++ "thousands": ",", ++ "lengthMenu": "_MENU_ ta yozuvni koʻrsatish", ++ "loadingRecords": "Yuklanmoqda...", ++ "processing": "Iltimos, kuting...", ++ "search": "Qidirish:", ++ "zeroRecords": "Mos keladigan yozuvlar topilmadi", ++ "paginate": { ++ "first": "Birinchi", ++ "last": "Oxirgi", ++ "next": "Keyingi", ++ "previous": "Oldingi" ++ }, ++ "aria": { ++ "sortAscending": ": ustunni oʻsish boʻyicha saralash uchun faollashtiring", ++ "sortDescending": ": ustunni kamayish boʻyicha saralash uchun faollashtiring" ++ } ++ }, ++ "debug": { ++ "architecture": "Arxitektura", ++ "chart_this_server": "Diagramma (bu server)", ++ "containers_info": "Konteyner ma'lumotlari", ++ "container_running": "Ishlamoqda", ++ "container_disabled": "Konteyner toʻxtatilgan yoki oʻchirilgan", ++ "container_stopped": "Toʻxtatilgan", ++ "cores": "Yadrolar", ++ "current_time": "Tizim vaqti", ++ "disk_usage": "Disk foydalanish", ++ "docs": "Hujjatlar", ++ "error_show_ip": "Ommaviy IP manzillarini aniqlab boʻlmadi", ++ "external_logs": "Tashqi jurnallar", ++ "history_all_servers": "Tarix (barcha serverlar)", ++ "in_memory_logs": "Xotiradagi jurnallar", ++ "last_modified": "Oxirgi oʻzgartirilgan", ++ "log_info": "

mailcow xotiradagi jurnallar Redis roʻyxatlarida toʻplanadi va har daqiqada hammomilik kamaytirish uchun LOG_LINES (%d) ga qisqartiriladi.\r\n
Xotiradagi jurnallar doimiy boʻlishi mumkin emas. Xotirada jurnal yurituvchi barcha ilovalar ham Docker daemoniga, demak standart jurnal yuritish drayveriga ham yozadi.\r\n
Xotiradagi jurnal turi konteynerlar bilan kichik muammolarni nosozliklarni bartaraf etish uchun ishlatilishi kerak.

\r\n

Tashqi jurnallar berilgan ilovaning API si orqali toʻplanadi.

\r\n

Statik jurnallar asosan faollik jurnallaridir, ular Dockerd ga yozilmaydi, lekin baribir doimiy boʻlishi kerak (API jurnallaridan tashqari).

", ++ "login_time": "Vaqt", ++ "logs": "Jurnallar", ++ "memory": "Xotira", ++ "online_users": "Onlayn foydalanuvchilar", ++ "restart_container": "Qayta ishga tushirish", ++ "service": "Xizmat", ++ "show_ip": "Ommaviy IP ni koʻrsatish", ++ "size": "Oʻlcham", ++ "started_at": "Boshlangan vaqt", ++ "started_on": "Boshlangan sana", ++ "static_logs": "Statik jurnallar", ++ "success": "Muvaffaqiyatli", ++ "system_containers": "Tizim va konteynerlar", ++ "timezone": "Vaqt mintaqasi", ++ "uptime": "Ishlash vaqti", ++ "update_available": "Yangilanish mavjud", ++ "no_update_available": "Tizim oxirgi versiyada", ++ "update_failed": "Yangilanishni tekshirib boʻlmadi", ++ "username": "Foydalanuvchi nomi", ++ "wip": "Hozir ishlab chiqilmoqda" ++ }, ++ "diagnostics": { ++ "cname_from_a": "Qiymat A/AAAA yozuvidan olingan. Yozuv toʻgʻri resursga ishora qilsa, bu qoʻllab-quvvatlanadi.", ++ "dns_records": "DNS yozuvlari", ++ "dns_records_24hours": "DNS ga kiritilgan oʻzgarishlar ushbu sahifada toʻgʻri aks ettirilishi uchun 24 soatgacha vaqt ketishi mumkinligini hisobga oling. Bu DNS yozuvlaringizni qanday sozlash kerakligini osongina koʻrish va barcha yozuvlaringiz DNS da toʻgʻri saqlanganligini tekshirish uchun moʻljallangan.", ++ "dns_records_data": "Toʻgʻri ma'lumot", ++ "dns_records_docs": "Iltimos, hujjatlarga ham murojaat qiling.", ++ "dns_records_name": "Nomi", ++ "dns_records_status": "Joriy holat", ++ "dns_records_type": "Tur", ++ "optional": "Bu yozuv ixtiyoriy." ++ }, ++ "edit": { ++ "acl": "ACL (Ruxsat)", ++ "active": "Faol", ++ "admin": "Administratorni tahrirlash", ++ "advanced_settings": "Kengaytirilgan sozlamalar", ++ "alias": "Taxallusni tahrirlash", ++ "allow_from_smtp": "Faqat ushbu IP larga SMTP dan foydalanishga ruxsat berish", ++ "allow_from_smtp_info": "Barcha joʻnatuvchilarga ruxsat berish uchun boʻsh qoldiring.
IPv4/IPv6 manzillari va tarmoqlari.", ++ "allowed_protocols": "Toʻgʻridan-toʻgʻri foydalanuvchi kirishi uchun ruxsat etilgan protokollar (ilova paroli protokollariga taʼsir qilmaydi)", ++ "app_name": "Ilova nomi", ++ "app_passwd": "Ilova paroli", ++ "app_passwd_protocols": "Ilova paroli uchun ruxsat etilgan protokollar", ++ "automap": "Papkalarni avtomatik xaritalashga harakat qilish (\"Sent items\", \"Sent\" => \"Sent\" va h.k.)", ++ "backup_mx_options": "Relay sozlamalari", ++ "bcc_dest_format": "BCC manzili bitta haqiqiy e-pochta manzili boʻlishi kerak.
Agar bir nechta manzilga nusxa joʻnatish kerak boʻlsa, taxallus yarating va shu yerda ishlating.", ++ "client_id": "Mijoz ID", ++ "client_secret": "Mijoz maxfiy soʻzi", ++ "comment_info": "Maxfiy izoh foydalanuvchiga koʻrinmaydi, ommaviy izoh esa foydalanuvchi koʻrinishida ustiga sichqoncha kelganda maslahat sifatida koʻrsatiladi", ++ "created_on": "Yaratilgan sana", ++ "custom_attributes": "Maxsus atributlar", ++ "delete1": "Tugatilgach manbadan oʻchirish", ++ "delete2": "Manbada boʻlmagan xabarlarni manzildan oʻchirish", ++ "delete2duplicates": "Manzildagi dublikatlarni oʻchirish", ++ "delete_ays": "Iltimos, oʻchirish jarayonini tasdiqlang.", ++ "description": "Tavsif", ++ "disable_login": "Kirishni taqiqlash (kiruvchi pochta hali ham qabul qilinadi)", ++ "domain": "Domenni tahrirlash", ++ "domain_admin": "Domen administratorini tahrirlash", ++ "domain_footer": "Domen boʻyicha pastki qism", ++ "domain_footer_html": "HTML pastki qism", ++ "domain_footer_info": "Domen boʻyicha pastki qismlar ushbu domendagi manzilga bog'liq barcha chiquvchi xatlarga qoʻshiladi.
Pastki qism uchun quyidagi oʻzgaruvchilarni ishlatish mumkin:", ++ "domain_footer_info_vars": { ++ "auth_user": "{= auth_user =} - MTA tomonidan belgilangan autentifikatsiya qilingan foydalanuvchi nomi", ++ "from_user": "{= from_user =} - Konvertning Kimdan qismi, masalan \"moo@mailcow.tld\" uchun \"moo\" qaytaradi", ++ "from_name": "{= from_name =} - Konvertning Kimdan ismi, masalan \"Mailcow <moo@mailcow.tld>\" uchun \"Mailcow\" qaytaradi", ++ "from_addr": "{= from_addr =} - Konvertning Kimdan manzili qismi", ++ "from_domain": "{= from_domain =} - Konvertning Kimdan domeni qismi", ++ "custom": "{= foo =} - Agar pochta qutisida \"bar\" qiymatli \"foo\" maxsus atributi boʻlsa \"bar\" qaytaradi" ++ }, ++ "domain_footer_plain": "PLAIN pastki qism", ++ "domain_footer_skip_replies": "Javob xatlarida pastki qismni e'tiborsiz qoldirish", ++ "domain_quota": "Domen kvotasi", ++ "domains": "Domenlar", ++ "dont_check_sender_acl": "%s domeni uchun joʻnatuvchi tekshiruvini oʻchirish (+ taxallus domenlari)", ++ "edit_alias_domain": "Taxallus domenini tahrirlash", ++ "encryption": "Shifrlash", ++ "exclude": "Obyektlarni istisno qilish (regex)", ++ "extended_sender_acl": "Tashqi joʻnatuvchi manzillari", ++ "extended_sender_acl_info": "DKIM domen kaliti mavjud boʻlsa, import qilinishi kerak.
\r\n Ushbu serverni mos SPF TXT yozuviga qoʻshishni unutmang.
\r\n Ushbu serverga tashqi manzil bilan ust-ust tushadigan domen yoki taxallus domeni qoʻshilganda, tashqi manzil olib tashlanadi.
\r\n *@domain.tld sifatida joʻnatishga ruxsat berish uchun @domain.tld dan foydalaning.", ++ "force_pw_update": "Keyingi kirishda parolni majburiy yangilash", ++ "force_pw_update_info": "Bu foydalanuvchi faqat %s ga kira oladi. Ilova parollari ishlash holatida qoladi.", ++ "footer_exclude": "Pastki qismdan istisno qilish", ++ "full_name": "Toʻliq ism", ++ "gal": "Global manzillar roʻyxati", ++ "gal_info": "GAL domenning barcha obyektlarini oʻz ichiga oladi va hech bir foydalanuvchi tomonidan tahrirlanmaydi. Oʻchirilsa, SOGodagi bandlik maʼlumotlari yoʻqoladi! Oʻzgarishlarni qoʻllash uchun SOGoni qayta ishga tushiring.", ++ "generate": "yaratish", ++ "grant_types": "Grant turlari", ++ "hostname": "Xost nomi", ++ "inactive": "Nofaol", ++ "internal": "Ichki", ++ "internal_info": "Ichki taxalluslarga faqat oʻz domeni yoki taxallus domenlaridan kirish mumkin.", ++ "sender_allowed": "Ushbu taxallus orqali joʻnatishga ruxsat berish", ++ "sender_allowed_info": "Oʻchirilgan boʻlsa, bu taxallus faqat xat qabul qilishi mumkin. Maxsus pochta qutilariga joʻnatishga ruxsat berish uchun joʻnatuvchi ACL dan foydalaning.", ++ "kind": "Turi", ++ "last_modified": "Oxirgi oʻzgartirilgan", ++ "lookup_mx": "Manzil — MX nomiga mos keladigan muntazam ifoda (.*\\.google\\.com — google.com bilan tugaydigan MX ga yoʻnaltirilgan barcha pochtani ushbu nuqta orqali yoʻnaltirish uchun)", ++ "mailbox": "Pochta qutisini tahrirlash", ++ "mailbox_quota_def": "Standart pochta qutisi kvotasi", ++ "mailbox_relayhost_info": "Faqat pochta qutisi va to'g'ridan-to'g'ri taxalluslarga qoʻllaniladi, domen relay xostini bekor qiladi.", ++ "mailbox_rename": "Pochta qutisini qayta nomlash", ++ "mailbox_rename_agree": "Men zaxira nusxasini yaratdim.", ++ "mailbox_rename_warning": "MUHIM! Pochta qutisini qayta nomlashdan oldin zaxira nusxasi yarating.", ++ "mailbox_rename_alias": "Taxallusni avtomatik yaratish", ++ "mailbox_rename_title": "Yangi mahalliy pochta qutisi nomi", ++ "max_aliases": "Maks. taxalluslar", ++ "max_mailboxes": "Mumkin boʻlgan maks. pochta qutilari", ++ "max_quota": "Bitta pochta qutisining maks. kvotasi (MiB)", ++ "maxage": "Masofadan soʻraladigan xabarlarning maksimal yoshi (kunlarda)
(0 = yoshni e'tiborsiz qoldirish)", ++ "maxbytespersecond": "Maks. soniyaga bayt
(0 = cheksiz)", ++ "mbox_rl_info": "Bu tezlik chegarasi SASL kirish nomiga qoʻllaniladi, u kirgan foydalanuvchi tomonidan ishlatiladigan har qanday \"from\" manziliga mos keladi. Pochta qutisi tezlik chegarasi domen boʻyicha tezlik chegarasini bekor qiladi.", ++ "mins_interval": "Oraliq (daqiqa)", ++ "mta_sts": "MTA-STS", ++ "mta_sts_info": "MTA-STS — pochta serverlari oʻrtasida xat yetkazib berishni haqiqiy sertifikatli TLS dan foydalanishga majburlovchi standart.
U DNSSEC mavjud emasligi yoki qoʻllab-quvvatlanmasligi sababli DANE imkoni boʻlmaganda ishlatiladi.
Eslatma: Agar qabul qiluvchi domen DNSSEC bilan DANE ni qoʻllab-quvvatlasa, DANE har doim afzal koʻriladi — MTA-STS faqat zaxira sifatida ishlaydi.", ++ "mta_sts_version": "Versiya", ++ "mta_sts_version_info": "MTA-STS standartining versiyasini belgilaydi — hozirda faqat STSv1 haqiqiy.", ++ "mta_sts_mode": "Rejim", ++ "mta_sts_mode_info": "Tanlash uchun uchta rejim mavjud:
  • testing — siyosat faqat kuzatiladi, buzilishlar taʼsir koʻrsatmaydi.
  • enforce — siyosat qatʼiy qoʻllaniladi, haqiqiy TLS siz ulanishlar rad etiladi.
  • none — siyosat eʼlon qilinadi, ammo qoʻllanilmaydi.
", ++ "mta_sts_max_age": "Maks. yosh", ++ "mta_sts_max_age_info": "Qabul qiluvchi pochta serverlari ushbu siyosatni qayta olishdan oldin keshlashi mumkin boʻlgan vaqt (soniyalarda).", ++ "mta_sts_mx": "MX server", ++ "mta_sts_mx_info": "Faqat aniq sanab oʻtilgan pochta server xost nomlariga joʻnatishga ruxsat beradi; joʻnatuvchi MTA DNS MX xost nomi siyosat roʻyxatiga mos kelishini tekshiradi va faqat haqiqiy TLS sertifikati bilan yetkazib berishga ruxsat beradi (MITM ga qarshi himoya qiladi).", ++ "mta_sts_mx_notice": "Bir nechta MX serverlar belgilanishi mumkin (vergul bilan ajratilgan).", ++ "multiple_bookings": "Bir nechta bandlovlar", ++ "none_inherit": "Hech biri / Meros qilib olish", ++ "nexthop": "Keyingi nuqta", ++ "password": "Parol", ++ "password_recovery_email": "Parolni tiklash e-pochtasi", ++ "password_repeat": "Tasdiqlash paroli (takrorlang)", ++ "previous": "Oldingi sahifa", ++ "private_comment": "Maxfiy izoh", ++ "public_comment": "Ommaviy izoh", ++ "pushover": "Pushover", ++ "pushover_evaluate_x_prio": "Yuqori muhimlikdagi xatni eskalatsiya qilish [X-Priority: 1]", ++ "pushover_info": "Push bildirishnoma sozlamalari %s ga taxalluslar bilan birga (umumiy, umumiy boʻlmagan, teglangan) yetkazib beriladigan barcha toza (spam boʻlmagan) xatlarga qoʻllaniladi.", ++ "pushover_only_x_prio": "Faqat yuqori muhimlikdagi xatlarni koʻrib chiqish [X-Priority: 1]", ++ "pushover_sender_array": "Faqat quyidagi joʻnatuvchi e-pochta manzillarini koʻrib chiqish (vergul bilan ajratilgan)", ++ "pushover_sender_regex": "Quyidagi joʻnatuvchi regexini koʻrib chiqish", ++ "pushover_text": "Bildirishnoma matni", ++ "pushover_title": "Bildirishnoma sarlavhasi", ++ "pushover_sound": "Tovush", ++ "pushover_vars": "Joʻnatuvchi filtri belgilanmagan boʻlsa, barcha xatlar koʻrib chiqiladi.
Regex filtrlari va aniq joʻnatuvchi tekshiruvlari alohida belgilanishi mumkin va ketma-ket koʻrib chiqiladi. Ular bir-biriga bogʻliq emas.
Matn va sarlavha uchun ishlatiladigan oʻzgaruvchilar (ma'lumotlarni himoya qilish siyosatiga e'tibor bering)", ++ "pushover_verify": "Maʼlumotlarni tekshirish", ++ "quota_mb": "Kvota (MiB)", ++ "quota_warning_bcc": "Kvota ogohlantirishi BCC", ++ "quota_warning_bcc_info": "Ogohlantirishlar alohida nusxa sifatida quyidagi qabul qiluvchilarga yuboriladi. Mavzu mos foydalanuvchi nomi bilan qavs ichida qoʻshib qoʻyiladi, masalan: Kvota ogohlantirishi (user@example.com).", ++ "ratelimit": "Tezlik chegarasi", ++ "redirect_uri": "Yoʻnaltirish/Qaytarish URL", ++ "relay_all": "Barcha qabul qiluvchilarni relay qilish", ++ "relay_all_info": "↪ Agar barcha qabul qiluvchilarni relay qilmaslikni tanlasangiz, relay qilinishi kerak boʻlgan har bir qabul qiluvchi uchun (\"koʻr\") pochta qutisi qoʻshishingiz kerak boʻladi.", ++ "relay_domain": "Ushbu domenni relay qilish", ++ "relay_transport_info": "
Maʼlumot
Bu domen uchun maxsus manzilga transport xaritalarini belgilashingiz mumkin. Agar oʻrnatilmagan boʻlsa, MX qidiruvi amalga oshiriladi.", ++ "relay_unknown_only": "Faqat mavjud boʻlmagan pochta qutilarini relay qilish. Mavjud pochta qutilari mahalliy yetkazib beriladi.", ++ "relayhost": "Joʻnatuvchiga bogʻliq transportlar", ++ "remove": "Olib tashlash", ++ "resource": "Resurs", ++ "save": "Oʻzgarishlarni saqlash", ++ "scope": "Qamrov", ++ "sender_acl": "Quyidagi sifatida joʻnatishga ruxsat berish", ++ "sender_acl_disabled": "Joʻnatuvchi tekshiruvi oʻchirilgan", ++ "sender_acl_info": "Agar A pochta qutisi foydalanuvchisi B pochta qutisi foydalanuvchisi sifatida joʻnatishga ruxsat etilgan boʻlsa, joʻnatuvchi manzili SOGo da tanlanadigan \"from\" maydoni sifatida avtomatik koʻrsatilmaydi.
\r\n B pochta qutisi foydalanuvchisi A pochta qutisi foydalanuvchisi oʻz manzilini joʻnatuvchi sifatida tanlay olishi uchun SOGo da delegatsiya yaratishi kerak. SOGo da pochta qutisini delegatsiya qilish uchun pochta koʻrinishida yuqori chap qismdagi pochta qutisi nomingiz oʻng tomonidagi menyudan (uch nuqta) foydalaning. Bu xatti-harakat taxallus manzillariga qoʻllanmaydi.", ++ "sieve_desc": "Qisqa tavsif", ++ "sieve_type": "Filtr turi", ++ "skipcrossduplicates": "Papkalararo dublikat xabarlarni oʻtkazib yuborish (birinchi kelgan, birinchi xizmatlanadi)", ++ "sogo_access": "SOGo ga toʻgʻridan-toʻgʻri yoʻnaltirish", ++ "sogo_access_info": "Tizimga kirgandan keyin foydalanuvchi avtomatik ravishda SOGo ga yoʻnaltiriladi.", ++ "sogo_visible": "Taxallus SOGo da koʻrinadi", ++ "sogo_visible_info": "Bu variant faqat SOGo da koʻrsatilishi mumkin boʻlgan obyektlarga taʼsir qiladi (kamida bitta mahalliy pochta qutisiga ishora qiluvchi umumiy yoki umumiy boʻlmagan taxallus manzillari). Yashirilgan boʻlsa, taxallus SOGo da tanlanadigan joʻnatuvchi sifatida koʻrinmaydi.", ++ "spam_alias": "Vaqt cheklangan taxallus manzillarini yaratish yoki oʻzgartirish", ++ "spam_filter": "Spam filtri", ++ "spam_policy": "Elementlarni ruxsat etilgan/qora roʻyxatga qoʻshish yoki olib tashlash", ++ "spam_score": "Maxsus spam bahosini oʻrnatish", ++ "subfolder2": "Manzilning subpapkasiga sinxronizatsiya qilish
(boʻsh = subpapkadan foydalanmang)", ++ "syncjob": "Sinxronizatsiya vazifasini tahrirlash", ++ "target_address": "Yoʻnaltirish manzil(lar)i (vergul bilan ajratilgan)", ++ "target_domain": "Maqsad domen", ++ "timeout1": "Masofaviy xostga ulanish vaqtining tugashi", ++ "timeout2": "Mahalliy xostga ulanish vaqtining tugashi", ++ "title": "Obyektni tahrirlash", ++ "unchanged_if_empty": "Oʻzgartirilmagan boʻlsa, boʻsh qoldiring", ++ "username": "Foydalanuvchi nomi", ++ "validate_save": "Tekshirish va saqlash" ++ }, ++ "fido2": { ++ "confirm": "Tasdiqlash", ++ "fido2_auth": "FIDO2 bilan kirish", ++ "fido2_success": "Qurilma muvaffaqiyatli roʻyxatdan oʻtkazildi", ++ "fido2_validation_failed": "Tekshirish muvaffaqiyatsiz", ++ "fn": "Doʻstona nom", ++ "known_ids": "Maʼlum ID lar", ++ "none": "Oʻchirilgan", ++ "register_status": "Roʻyxatga olish holati", ++ "rename": "Qayta nomlash", ++ "set_fido2": "FIDO2 qurilmasini roʻyxatdan oʻtkazish", ++ "set_fido2_touchid": "Apple M1 da Touch ID ni roʻyxatdan oʻtkazish", ++ "set_fn": "Doʻstona nomni oʻrnatish", ++ "start_fido2_validation": "FIDO2 tekshiruvini boshlash" ++ }, ++ "footer": { ++ "cancel": "Bekor qilish", ++ "confirm_delete": "Oʻchirishni tasdiqlash", ++ "delete_now": "Hozir oʻchirish", ++ "delete_these_items": "Iltimos, quyidagi obyekt ID siga oʻzgarishlaringizni tasdiqlang", ++ "hibp_check": "haveibeenpwned.com ga qarshi tekshirish", ++ "hibp_nok": "Mos keldi! Bu xavfli parol boʻlishi mumkin!", ++ "hibp_ok": "Mos kelmadi.", ++ "loading": "Iltimos, kuting...", ++ "nothing_selected": "Hech narsa tanlanmadi", ++ "restart_container": "Konteynerni qayta ishga tushirish", ++ "restart_container_info": "Muhim: Yumshoq qayta ishga tushirish biroz vaqt olishi mumkin, iltimos uning tugashini kuting.", ++ "restart_now": "Hozir qayta ishga tushirish", ++ "restarting_container": "Konteyner qayta ishga tushirilmoqda, bu biroz vaqt olishi mumkin" ++ }, ++ "header": { ++ "administration": "Konfiguratsiya va tafsilotlar", ++ "apps": "Ilovalar", ++ "debug": "Maʼlumot", ++ "email": "E-pochta", ++ "mailcow_system": "Tizim", ++ "mailcow_config": "Konfiguratsiya", ++ "quarantine": "Karantin", ++ "restart_netfilter": "Netfilterni qayta ishga tushirish", ++ "restart_sogo": "SOGoni qayta ishga tushirish", ++ "user_settings": "Foydalanuvchi sozlamalari" ++ }, ++ "info": { ++ "awaiting_tfa_confirmation": "TFA tasdiqlanishi kutilmoqda", ++ "no_action": "Amal qoʻllanib boʻlmaydi", ++ "session_expires": "Sessiyangiz taxminan 15 soniyadan keyin tugaydi" ++ }, ++ "login": { ++ "back_to_mailcow": "mailcow ga qaytish", ++ "delayed": "Kirish %s soniyaga kechiktirildi.", ++ "fido2_webauthn": "FIDO2/WebAuthn kirish", ++ "forgot_password": "> Parolni unutdingizmi?", ++ "invalid_pass_reset_token": "Parolni tiklash tokeni noto'g'ri yoki muddati tugagan.
Iltimos, yangi parolni tiklash havolasini soʻrang.", ++ "login": "Kirish", ++ "login_linkstext": "Toʻgʻri kirish emasmi?", ++ "login_usertext": "Foydalanuvchi sifatida kirish", ++ "login_domainadmintext": "Domen administratori sifatida kirish", ++ "login_admintext": "Administrator sifatida kirish", ++ "login_user": "Foydalanuvchi kirishi", ++ "login_dadmin": "Domen-administratori kirishi", ++ "login_admin": "Administrator kirishi", ++ "mobileconfig_info": "Soʻralgan Apple ulanish profilini yuklab olish uchun pochta qutisi foydalanuvchisi sifatida kiring.", ++ "new_password": "Yangi parol", ++ "new_password_confirm": "Yangi parolni tasdiqlang", ++ "other_logins": "yoki quyidagi orqali kiring", ++ "password": "Parol", ++ "reset_password": "Parolni tiklash", ++ "request_reset_password": "Parol oʻzgartirishni soʻrash", ++ "username": "Foydalanuvchi nomi", ++ "email": "E-pochta manzili" ++ }, ++ "mailbox": { ++ "action": "Amal", ++ "activate": "Faollashtirish", ++ "active": "Faol", ++ "add": "Qoʻshish", ++ "add_alias": "Taxallus qoʻshish", ++ "add_alias_expand": "Taxallusni taxallus domenlari boʻylab kengaytirish", ++ "add_bcc_entry": "BCC xaritasi qoʻshish", ++ "add_domain": "Domen qoʻshish", ++ "add_domain_alias": "Domen taxallusini qoʻshish", ++ "add_domain_record_first": "Iltimos, avval domen qoʻshing", ++ "add_filter": "Filtr qoʻshish", ++ "add_mailbox": "Pochta qutisi qoʻshish", ++ "add_recipient_map_entry": "Qabul qiluvchi xaritasini qoʻshish", ++ "add_resource": "Resurs qoʻshish", ++ "add_template": "Shablon qoʻshish", ++ "add_tls_policy_map": "TLS siyosati xaritasini qoʻshish", ++ "address_rewriting": "Manzilni qayta yozish", ++ "alias": "Taxallus", ++ "alias_domain_alias_hint": "Taxalluslar domen taxalluslariga avtomatik qoʻllanilmaydi. my-alias@domain taxallus manzili my-alias@alias-domain manzilini qoplamaydi (bu yerda \"alias-domain\" — \"domain\" uchun tasavvur qilingan taxallus domeni).
Tashqi pochta qutisiga xatni yoʻnaltirish uchun sieve filtridan foydalaning (\"Filtrlar\" yorligʻiga qarang yoki SOGo -> Forwarder dan foydalaning). Yoʻq taxalluslarni avtomatik qoʻshish uchun \"Taxallusni taxallus domenlari boʻylab kengaytirish\" dan foydalaning.", ++ "alias_domain_backupmx": "Relay domeni uchun taxallus domeni nofaol", ++ "aliases": "Taxalluslar", ++ "all_domains": "Barcha domenlar", ++ "allow_from_smtp": "Faqat ushbu IP larga SMTP dan foydalanishga ruxsat berish", ++ "allow_from_smtp_info": "Barcha joʻnatuvchilarga ruxsat berish uchun boʻsh qoldiring.
IPv4/IPv6 manzillari va tarmoqlari.", ++ "allowed_protocols": "Ruxsat etilgan protokollar", ++ "backup_mx": "Relay domeni", ++ "bcc": "BCC", ++ "bcc_destination": "BCC manzili", ++ "bcc_destinations": "BCC manzili", ++ "bcc_info": "BCC xaritalari barcha xabarlarning nusxalarini boshqa manzilga jimgina yoʻnaltirish uchun ishlatiladi. Qabul qiluvchi xaritasi turi yozuvi mahalliy manzil xatning qabul qiluvchisi sifatida ishlaganda ishlatiladi. Joʻnatuvchi xaritalari ham xuddi shu tamoyilga muvofiq ishlaydi.
\r\n Mahalliy manzilga yetkazib berish muvaffaqiyatsiz boʻlsa, xabar berilmaydi.", ++ "bcc_local_dest": "Mahalliy manzil", ++ "bcc_map": "BCC xaritasi", ++ "bcc_map_type": "BCC turi", ++ "bcc_maps": "BCC xaritalari", ++ "bcc_rcpt_map": "Qabul qiluvchi xaritasi", ++ "bcc_sender_map": "Joʻnatuvchi xaritasi", ++ "bcc_to_rcpt": "Qabul qiluvchi xaritasi turiga oʻtish", ++ "bcc_to_sender": "Joʻnatuvchi xaritasi turiga oʻtish", ++ "bcc_type": "BCC turi", ++ "booking_null": "Doimo boʻsh sifatida koʻrsatish", ++ "booking_0_short": "Doimo boʻsh", ++ "booking_custom": "Maxsus bandlovlar soni bilan qatʼiy cheklash", ++ "booking_custom_short": "Qatʼiy chegara", ++ "booking_ltnull": "Cheksiz, lekin bandlangan boʻlsa band sifatida koʻrsatish", ++ "booking_lt0_short": "Yumshoq chegara", ++ "catch_all": "Hammasini-qabul qilish", ++ "created_on": "Yaratilgan sana", ++ "daily": "Kunlik", ++ "deactivate": "Oʻchirish", ++ "description": "Tavsif", ++ "disable_login": "Kirishni taqiqlash (kiruvchi pochta hali ham qabul qilinadi)", ++ "disable_x": "Oʻchirish", ++ "dkim_domains_selector": "Tanlovchi", ++ "dkim_key_length": "DKIM kalit uzunligi (bit)", ++ "domain": "Domen", ++ "domain_admins": "Domen administratorlari", ++ "domain_aliases": "Domen taxalluslari", ++ "domain_templates": "Domen shablonlari", ++ "domain_quota": "Kvota", ++ "domain_quota_total": "Umumiy domen kvotasi", ++ "domains": "Domenlar", ++ "edit": "Tahrirlash", ++ "empty": "Natijalar yoʻq", ++ "enable_x": "Yoqish", ++ "excludes": "Istisnolar", ++ "filter_table": "Filtr jadvali", ++ "filters": "Filtrlar", ++ "fname": "Toʻliq ism", ++ "force_pw_update": "Keyingi kirishda parolni majburiy yangilash", ++ "gal": "Global manzillar roʻyxati", ++ "goto_ham": "ham sifatida oʻrgatish", ++ "goto_spam": "spam sifatida oʻrgatish", ++ "hourly": "Soatlik", ++ "iam": "Identifikatsiya provayderi", ++ "in_use": "Foydalanilmoqda (%)", ++ "inactive": "Nofaol", ++ "insert_preset": "Misol presetini kiritish \"%s\"", ++ "internal": "Ichki", ++ "kind": "Turi", ++ "last_mail_login": "Oxirgi pochta kirishi", ++ "last_modified": "Oxirgi oʻzgartirilgan", ++ "last_pw_change": "Oxirgi parol oʻzgarishi", ++ "last_run": "Oxirgi ishga tushirilgan", ++ "last_run_reset": "Keyingisini rejalashtirish", ++ "mailbox": "Pochta qutisi", ++ "mailbox_defaults": "Standart sozlamalar", ++ "mailbox_defaults_info": "Yangi pochta qutilari uchun standart sozlamalarni belgilang.", ++ "mailbox_defquota": "Standart pochta qutisi oʻlchami", ++ "mailbox_templates": "Pochta qutisi shablonlari", ++ "mailbox_quota": "Pochta qutisining maks. oʻlchami", ++ "mailboxes": "Pochta qutilari", ++ "max_aliases": "Maks. taxalluslar", ++ "max_mailboxes": "Mumkin boʻlgan maks. pochta qutilari", ++ "max_quota": "Bitta pochta qutisining maks. kvotasi", ++ "mins_interval": "Oraliq (daqiqa)", ++ "msg_num": "Xabar #", ++ "multiple_bookings": "Bir nechta bandlovlar", ++ "never": "Hech qachon", ++ "no": "✕", ++ "no_record": "%s obyekti uchun yozuv yoʻq", ++ "no_record_single": "Yozuv yoʻq", ++ "open_logs": "Jurnallarni ochish", ++ "owner": "Egasi", ++ "private_comment": "Maxfiy izoh", ++ "public_comment": "Ommaviy izoh", ++ "q_add_header": "Junk papkasiga koʻchirilganda", ++ "q_all": " Junk papkasiga koʻchirilganda va rad etilganda", ++ "q_reject": "rad etilganda", ++ "quarantine_category": "Karantin bildirishnoma turkumi", ++ "quarantine_notification": "Karantin bildirishnomalari", ++ "quick_actions": "Amallar", ++ "recipient": "Qabul qiluvchi", ++ "recipient_map": "Qabul qiluvchi xaritasi", ++ "recipient_map_info": "Qabul qiluvchi xaritalari xabar yetkazib berilishidan oldin manzilni almashtirish uchun ishlatiladi.", ++ "recipient_map_new": "Yangi qabul qiluvchi", ++ "recipient_map_new_info": "Qabul qiluvchi xaritasi manzili haqiqiy e-pochta manzili yoki domen nomi boʻlishi kerak.", ++ "recipient_map_old": "Asl qabul qiluvchi", ++ "recipient_map_old_info": "Qabul qiluvchi xaritasining asl manzili haqiqiy e-pochta manzili yoki domen nomi boʻlishi kerak.", ++ "recipient_maps": "Qabul qiluvchi xaritalari", ++ "relay_all": "Barcha qabul qiluvchilarni relay qilish", ++ "relay_unknown": "Nomaʼlum pochta qutilarini relay qilish", ++ "remove": "Olib tashlash", ++ "resources": "Resurslar", ++ "running": "Ishlamoqda", ++ "sender": "Joʻnatuvchi", ++ "set_postfilter": "Postfiltr sifatida belgilash", ++ "set_prefilter": "Prefiltr sifatida belgilash", ++ "sieve_info": "Bitta foydalanuvchi uchun bir nechta filtrlarni saqlash mumkin, lekin bir vaqtning oʻzida faqat bitta prefiltr va bitta postfiltr faol boʻlishi mumkin.
\r\nHar bir filtr tasvirlangan tartibda qayta ishlanadi. Muvaffaqiyatsiz skript ham, chiqarilgan \"keep;\" ham keyingi skriptlarning qayta ishlanishini toʻxtatmaydi. Global sieve skriptlariga oʻzgartirishlar Dovecot ni qayta ishga tushirishni keltirib chiqaradi.

Global sieve prefilter • Prefilter • Foydalanuvchi skriptlari • Postfilter • Global sieve postfilter", ++ "sieve_preset_1": "Xavfli boʻlishi mumkin boʻlgan fayl turlari bilan xatlarni rad etish", ++ "sieve_preset_2": "Aniq joʻnatuvchining xatini har doim oʻqilgan deb belgilash", ++ "sieve_preset_3": "Jimgina rad etish, keyingi sieve qayta ishlashini toʻxtatish", ++ "sieve_preset_4": "INBOX ga joylash, sieve filtrlari tomonidan keyingi qayta ishlashni oʻtkazib yuborish", ++ "sieve_preset_5": "Avto-javob (taʼtil)", ++ "sieve_preset_6": "Javob bilan xatni rad etish", ++ "sieve_preset_7": "Yoʻnaltirish va saqlash/tashlash", ++ "sieve_preset_8": "Aniq joʻnatuvchining xatini yoʻnaltirish, oʻqilgan deb belgilash va subpapkaga saralash", ++ "sieve_preset_header": "Iltimos, quyidagi misol presetlariga qarang. Batafsil maʼlumot uchun Wikipediaga qarang.", ++ "sogo_visible": "Taxallus SOGo da koʻrinadi", ++ "sogo_visible_n": "Taxallusni SOGo da yashirish", ++ "sogo_visible_y": "Taxallusni SOGo da koʻrsatish", ++ "spam_aliases": "Vaqt. taxallus", ++ "stats": "Statistika", ++ "status": "Holat", ++ "sync_jobs": "Sinxronizatsiya vazifalari", ++ "syncjob_check_log": "Jurnalni tekshirish", ++ "syncjob_last_run_result": "Oxirgi ishga tushirilgan natija", ++ "syncjob_EX_OK": "Muvaffaqiyatli", ++ "syncjob_EXIT_CONNECTION_FAILURE": "Ulanish muammosi", ++ "syncjob_EXIT_TLS_FAILURE": "Shifrlangan ulanish bilan muammo", ++ "syncjob_EXIT_AUTHENTICATION_FAILURE": "Autentifikatsiya muammosi", ++ "syncjob_EXIT_OVERQUOTA": "Maqsad pochta qutisi kvotadan oshib ketdi", ++ "syncjob_EXIT_CONNECTION_FAILURE_HOST1": "Masofaviy serverga ulanib boʻlmadi", ++ "syncjob_EXIT_AUTHENTICATION_FAILURE_USER1": "Notoʻgʻri foydalanuvchi nomi yoki parol", ++ "table_size": "Jadval oʻlchami", ++ "table_size_show_n": "%s ta element koʻrsatish", ++ "target_address": "Yoʻnaltirish manzili", ++ "target_domain": "Maqsad domen", ++ "templates": "Shablonlar", ++ "template": "Shablon", ++ "tls_enforce_in": "Kiruvchi TLS ni majburlash", ++ "tls_enforce_out": "Chiquvchi TLS ni majburlash", ++ "tls_map_dest": "Manzil", ++ "tls_map_dest_info": "Misollar: example.org, .example.org, [mail.example.org]:25", ++ "tls_map_parameters": "Parametrlar", ++ "tls_map_parameters_info": "Boʻsh yoki parametrlar, masalan: protocols=!SSLv2 ciphers=medium exclude=3DES", ++ "tls_map_policy": "Siyosat", ++ "tls_policy_maps": "TLS siyosati xaritalari", ++ "tls_policy_maps_enforced_tls": "Bu siyosatlar chiquvchi TLS ulanishlarini majburlovchi pochta qutisi foydalanuvchilari uchun ham xatti-harakatni bekor qiladi. Agar quyida siyosat boʻlmasa, bu foydalanuvchilar smtp_tls_mandatory_protocols va smtp_tls_mandatory_ciphers sifatida belgilangan standart qiymatlarni qoʻllaydi.", ++ "tls_policy_maps_info": "Bu siyosat xaritasi foydalanuvchining TLS siyosati sozlamalaridan mustaqil ravishda chiquvchi TLS transport qoidalarini bekor qiladi.
\r\n Batafsil maʼlumot uchun \"smtp_tls_policy_maps\" hujjatlarini tekshiring.", ++ "tls_policy_maps_long": "Chiquvchi TLS siyosati xaritasi bekor qilishlari", ++ "toggle_all": "Hammasini almashtirish", ++ "username": "Foydalanuvchi nomi", ++ "waiting": "Kutilmoqda", ++ "weekly": "Haftalik", ++ "yes": "✓" ++ }, ++ "oauth2": { ++ "access_denied": "OAuth2 orqali kirishga ruxsat berish uchun pochta qutisi egasi sifatida kiring.", ++ "authorize_app": "Ilovaga ruxsat berish", ++ "deny": "Rad etish", ++ "permit": "Ilovaga ruxsat berish", ++ "profile": "Profil", ++ "profile_desc": "Shaxsiy maʼlumotlarni koʻrish: foydalanuvchi nomi, toʻliq ism, yaratilgan, oʻzgartirilgan, faol", ++ "scope_ask_permission": "Ilova quyidagi ruxsatlarni soʻradi" ++ }, ++ "quarantine": { ++ "action": "Amal", ++ "atts": "Ilovalar", ++ "check_hash": "VT da fayl hashini qidirish", ++ "confirm": "Tasdiqlash", ++ "confirm_delete": "Ushbu elementni oʻchirishni tasdiqlang.", ++ "danger": "Xavf", ++ "deliver_inbox": "Inbox ga yetkazib berish", ++ "disabled_by_config": "Joriy tizim konfiguratsiyasi karantin funksiyasini oʻchirib qoʻyadi. Iltimos, karantin elementlari uchun \"pochta qutisi boʻyicha saqlash\" va \"maksimal oʻlcham\"ni oʻrnating.", ++ "download_eml": "Yuklab olish (.eml)", ++ "empty": "Natijalar yoʻq", ++ "high_danger": "Yuqori", ++ "info": "Maʼlumot", ++ "junk_folder": "Junk papkasi", ++ "learn_spam_delete": "Spam sifatida oʻrgatish va oʻchirish", ++ "low_danger": "Past", ++ "medium_danger": "Oʻrtacha", ++ "neutral_danger": "Neytral", ++ "notified": "Xabar berildi", ++ "qhandler_success": "Soʻrov tizimga muvaffaqiyatli yuborildi. Endi oynani yopishingiz mumkin.", ++ "qid": "Rspamd QID", ++ "qinfo": "Karantin tizimi rad etilgan xatni (joʻnatuvchiga xat yetkazib berilgandek taassurot bermay) hamda pochta qutisining Junk papkasiga nusxa sifatida yetkazib berilgan xatni maʼlumotlar bazasiga saqlaydi.\r\n
\"Spam sifatida oʻrgatish va oʻchirish\" xabarni Bayesian teoremasi orqali spam sifatida oʻrgatadi va kelajakda oʻxshash xabarlarni rad etish uchun fuzzy hashlarni hisoblaydi.\r\n
Bir nechta xabarlarni oʻrgatish — tizimingizga qarab — vaqt talab qilishi mumkinligini unutmang.
Qora roʻyxatdagi elementlar karantindan istisno qilinadi.", ++ "qitem": "Karantin elementi", ++ "quarantine": "Karantin", ++ "quick_actions": "Amallar", ++ "quick_delete_link": "Tezkor oʻchirish havolasini ochish", ++ "quick_info_link": "Maʼlumot havolasini ochish", ++ "quick_release_link": "Tezkor chiqarish havolasini ochish", ++ "rcpt": "Qabul qiluvchi", ++ "received": "Qabul qilingan", ++ "recipients": "Qabul qiluvchilar", ++ "refresh": "Yangilash", ++ "rejected": "Rad etilgan", ++ "release": "Chiqarish", ++ "release_body": "Xabaringizni ushbu xabarga eml fayl sifatida ilova qildik.", ++ "release_subject": "Potensial xavfli karantin elementi %s", ++ "remove": "Olib tashlash", ++ "rewrite_subject": "Mavzuni qayta yozish", ++ "rspamd_result": "Rspamd natijasi", ++ "sender": "Joʻnatuvchi (SMTP)", ++ "sender_header": "Joʻnatuvchi (\"From\" sarlavhasi)", ++ "settings_info": "Karantinga olinadigan maksimal elementlar soni: %s
Maksimal e-pochta oʻlchami: %s MiB", ++ "show_item": "Elementni koʻrsatish", ++ "spam": "Spam", ++ "spam_score": "Baho", ++ "subj": "Mavzu", ++ "table_size": "Jadval oʻlchami", ++ "table_size_show_n": "%s ta element koʻrsatish", ++ "text_from_html_content": "Mazmun (oʻzgartirilgan html)", ++ "text_plain_content": "Mazmun (text/plain)", ++ "toggle_all": "Hammasini almashtirish", ++ "type": "Tur" ++ }, ++ "queue": { ++ "delete": "Hammasini oʻchirish", ++ "flush": "Navbatni tozalash", ++ "info": "Pochta navbati yetkazib berilishini kutayotgan barcha xatlarni oʻz ichiga oladi. Agar e-pochta uzoq vaqt davomida pochta navbatida tursa, u tizim tomonidan avtomatik ravishda oʻchiriladi.
Tegishli xatning xato xabari xat nima uchun yetkazib berilmaganligi haqida maʼlumot beradi.", ++ "legend": "Pochta navbati amallari funksiyalari:", ++ "ays": "Iltimos, joriy navbatdagi barcha elementlarni oʻchirishni tasdiqlang.", ++ "deliver_mail": "Yetkazib berish", ++ "deliver_mail_legend": "Tanlangan xatlarni qayta yetkazib berishga harakat qiladi.", ++ "hold_mail": "Ushlab turish", ++ "hold_mail_legend": "Tanlangan xatlarni ushlab turadi. (Keyingi yetkazib berish urinishlarining oldini oladi)", ++ "queue_manager": "Navbat menejeri", ++ "show_message": "Xabarni koʻrsatish", ++ "unban": "navbatdan blokdan chiqarish", ++ "unhold_mail": "Ushlab turishni bekor qilish", ++ "unhold_mail_legend": "Tanlangan xatlarni yetkazib berish uchun chiqaradi. (Avval ushlab turish talab qilinadi)" ++ }, ++ "ratelimit": { ++ "disabled": "Oʻchirilgan", ++ "second": "xabarlar / soniya", ++ "minute": "xabarlar / daqiqa", ++ "hour": "xabarlar / soat", ++ "day": "xabarlar / kun" ++ }, ++ "start": { ++ "help": "Yordam panelini koʻrsatish/yashirish", ++ "imap_smtp_server_auth_info": "Iltimos, toʻliq e-pochta manzilingiz va PLAIN autentifikatsiya mexanizmidan foydalaning.
\r\nKirish maʼlumotlaringiz server tomonidagi majburiy shifrlash orqali shifrlanadi." ++ }, ++ "success": { ++ "acl_saved": "%s obyekti uchun ACL saqlandi", ++ "admin_added": "Administrator %s qoʻshildi", ++ "admin_api_modified": "API ga oʻzgarishlar saqlandi", ++ "admin_modified": "Administrator oʻzgarishlari saqlandi", ++ "admin_removed": "Administrator %s olib tashlandi", ++ "alias_added": "Taxallus manzili %s (%d) qoʻshildi", ++ "alias_domain_removed": "Taxallus domeni %s olib tashlandi", ++ "alias_modified": "Taxallus manzili %s ga oʻzgarishlar saqlandi", ++ "alias_removed": "Taxallus %s olib tashlandi", ++ "aliasd_added": "Taxallus domeni %s qoʻshildi", ++ "aliasd_modified": "Taxallus domeni %s ga oʻzgarishlar saqlandi", ++ "app_links": "Ilova havolalariga oʻzgarishlar saqlandi", ++ "app_passwd_added": "Yangi ilova paroli qoʻshildi", ++ "app_passwd_removed": "Ilova paroli ID %s olib tashlandi", ++ "bcc_deleted": "BCC xaritasi yozuvlari oʻchirildi: %s", ++ "bcc_edited": "BCC xaritasi yozuvi %s tahrirlandi", ++ "bcc_saved": "BCC xaritasi yozuvi saqlandi", ++ "cors_headers_edited": "CORS sozlamalari saqlandi", ++ "custom_login_modified": "Kirishni sozlash muvaffaqiyatli saqlandi", ++ "db_init_complete": "Maʼlumotlar bazasini ishga tushirish tugadi", ++ "delete_filter": "Filtr ID %s oʻchirildi", ++ "delete_filters": "Filtrlar oʻchirildi: %s", ++ "deleted_syncjob": "Sinxronizatsiya vazifasi ID %s oʻchirildi", ++ "deleted_syncjobs": "Sinxronizatsiya vazifalari oʻchirildi: %s", ++ "dkim_added": "DKIM kaliti %s saqlandi", ++ "domain_add_dkim_available": "DKIM kaliti allaqachon mavjud edi", ++ "dkim_duplicated": "%s domeni uchun DKIM kaliti %s ga nusxalandi", ++ "dkim_removed": "DKIM kaliti %s olib tashlandi", ++ "domain_added": "Domen %s qoʻshildi", ++ "domain_admin_added": "Domen administratori %s qoʻshildi", ++ "domain_admin_modified": "Domen administratori %s ga oʻzgarishlar saqlandi", ++ "domain_admin_removed": "Domen administratori %s olib tashlandi", ++ "domain_footer_modified": "Domen pastki qismi %s ga oʻzgarishlar saqlandi", ++ "domain_modified": "Domen %s ga oʻzgarishlar saqlandi", ++ "domain_removed": "Domen %s olib tashlandi", ++ "dovecot_restart_success": "Dovecot muvaffaqiyatli qayta ishga tushirildi", ++ "eas_reset": "%s foydalanuvchisi uchun ActiveSync qurilmalari tiklandi", ++ "f2b_banlist_refreshed": "Banlist ID muvaffaqiyatli yangilandi.", ++ "f2b_modified": "Fail2ban parametrlariga oʻzgarishlar saqlandi", ++ "forwarding_host_added": "Yoʻnaltirish xosti %s qoʻshildi", ++ "forwarding_host_removed": "Yoʻnaltirish xosti %s olib tashlandi", ++ "global_filter_written": "Filtr faylga muvaffaqiyatli yozildi", ++ "hash_deleted": "Hash oʻchirildi", ++ "iam_test_connection": "Ulanish muvaffaqiyatli", ++ "ip_check_opt_in_modified": "IP tekshiruvi muvaffaqiyatli saqlandi", ++ "item_deleted": "Element %s muvaffaqiyatli oʻchirildi", ++ "item_released": "Element %s chiqarildi", ++ "items_deleted": "Element %s muvaffaqiyatli oʻchirildi", ++ "items_released": "Tanlangan elementlar chiqarildi", ++ "learned_ham": "ID %s ham sifatida muvaffaqiyatli oʻrgatildi", ++ "license_modified": "Litsenziyaga oʻzgarishlar saqlandi", ++ "logged_in_as": "%s sifatida tizimga kirildi", ++ "mailbox_added": "Pochta qutisi %s qoʻshildi", ++ "mailbox_modified": "Pochta qutisi %s ga oʻzgarishlar saqlandi", ++ "mailbox_removed": "Pochta qutisi %s olib tashlandi", ++ "mailbox_renamed": "Pochta qutisi %s dan %s ga qayta nomlandi", ++ "nginx_reloaded": "Nginx qayta yuklandi", ++ "object_modified": "Obyekt %s ga oʻzgarishlar saqlandi", ++ "password_policy_saved": "Parol siyosati muvaffaqiyatli saqlandi", ++ "password_changed_success": "Parol muvaffaqiyatli oʻzgartirildi", ++ "pushover_settings_edited": "Pushover sozlamalari muvaffaqiyatli oʻrnatildi, iltimos maʼlumotlarni tekshiring.", ++ "qlearn_spam": "Xabar ID %s spam sifatida oʻrgatildi va oʻchirildi", ++ "queue_command_success": "Navbat buyrugʻi muvaffaqiyatli yakunlandi", ++ "recipient_map_entry_deleted": "Qabul qiluvchi xaritasi ID %s oʻchirildi", ++ "recipient_map_entry_saved": "Qabul qiluvchi xaritasi yozuvi \"%s\" saqlandi", ++ "recovery_email_sent": "Tiklash e-pochtasi %s ga yuborildi", ++ "relayhost_added": "Xarita yozuvi %s qoʻshildi", ++ "relayhost_removed": "Xarita yozuvi %s olib tashlandi", ++ "reset_main_logo": "Standart logotipga qaytarildi", ++ "resource_added": "Resurs %s qoʻshildi", ++ "resource_modified": "Pochta qutisi %s ga oʻzgarishlar saqlandi", ++ "resource_removed": "Resurs %s olib tashlandi", ++ "rl_saved": "%s obyekti uchun tezlik chegarasi saqlandi", ++ "rspamd_ui_pw_set": "Rspamd UI paroli muvaffaqiyatli oʻrnatildi", ++ "saved_settings": "Sozlamalar saqlandi", ++ "settings_map_added": "Sozlamalar xaritasi yozuvi qoʻshildi", ++ "settings_map_removed": "Sozlamalar xaritasi ID %s olib tashlandi", ++ "sogo_profile_reset": "%s foydalanuvchisi uchun SOGo profili tiklandi", ++ "template_added": "Shablon %s qoʻshildi", ++ "template_modified": "Shablon %s ga oʻzgarishlar saqlandi", ++ "template_removed": "Shablon ID %s oʻchirildi", ++ "tls_policy_map_entry_deleted": "TLS siyosati xaritasi ID %s oʻchirildi", ++ "tls_policy_map_entry_saved": "TLS siyosati xaritasi yozuvi \"%s\" saqlandi", ++ "ui_texts": "UI matnlariga oʻzgarishlar saqlandi", ++ "upload_success": "Fayl muvaffaqiyatli yuklandi", ++ "verified_fido2_login": "FIDO2 kirishi tasdiqlandi", ++ "verified_totp_login": "TOTP kirishi tasdiqlandi", ++ "verified_webauthn_login": "WebAuthn kirishi tasdiqlandi", ++ "verified_yotp_login": "Yubico OTP kirishi tasdiqlandi" ++ }, ++ "tfa": { ++ "authenticators": "Autentifikatorlar", ++ "api_register": "%s Yubico Cloud API dan foydalanadi. Iltimos, kalitingiz uchun API kalitini bu yerdan oling", ++ "confirm": "Tasdiqlash", ++ "confirm_totp_token": "Iltimos, yaratilgan tokenni kiritib oʻzgarishlaringizni tasdiqlang", ++ "delete_tfa": "TFA ni oʻchirish", ++ "disable_tfa": "Keyingi muvaffaqiyatli kirishgacha TFA ni oʻchirish", ++ "force_tfa": "Kirishda 2FA roʻyxatdan oʻtkazishni majburlash", ++ "force_tfa_info": "Foydalanuvchidan panelga kirishdan oldin ikki faktorli autentifikatsiyani sozlash talab qilinadi.", ++ "setup_title": "Ikki faktorli autentifikatsiya talab qilinadi", ++ "setup_required": "Hisobingiz ikki faktorli autentifikatsiyani talab qiladi. Davom etish uchun 2FA usulini sozlang.", ++ "cancel_setup": "Bekor qilish va chiqish", ++ "enter_qr_code": "Agar qurilmangiz QR kodlarni skanerlay olmasa, TOTP kodingiz", ++ "error_code": "Xato kodi", ++ "init_webauthn": "Ishga tushirilmoqda, iltimos kuting...", ++ "key_id": "Qurilmangiz uchun identifikator", ++ "key_id_totp": "Kalitingiz uchun identifikator", ++ "none": "Oʻchirish", ++ "reload_retry": "- (xato davom etsa, brauzerni qayta yuklang)", ++ "scan_qr_code": "Iltimos, quyidagi kodni autentifikator ilovangiz bilan skanerlang yoki kodni qoʻlda kiriting.", ++ "select": "Iltimos, tanlang", ++ "set_tfa": "Ikki faktorli autentifikatsiya usulini oʻrnatish", ++ "start_webauthn_validation": "Tekshiruvni boshlash", ++ "tfa": "Ikki faktorli autentifikatsiya", ++ "tfa_token_invalid": "TFA tokeni noto'g'ri", ++ "totp": "Vaqt asosidagi OTP (Google Authenticator, Authy va h.k.)", ++ "u2f_deprecated": "Sizning kalitingiz eskirgan U2F usulidan foydalanib roʻyxatdan oʻtkazilganga oʻxshaydi. Biz siz uchun ikki faktorli autentifikatsiyani oʻchirib qoʻyamiz va kalitingizni oʻchiramiz.", ++ "u2f_deprecated_important": "Iltimos, kalitingizni admin panelida yangi WebAuthn usuli bilan roʻyxatdan oʻtkazing.", ++ "webauthn": "WebAuthn autentifikatsiya", ++ "waiting_usb_auth": "USB qurilmasi kutilmoqda...

Iltimos, hozir USB qurilmangizdagi tugmani bosing.", ++ "waiting_usb_register": "USB qurilmasi kutilmoqda...

Iltimos, yuqorida parolingizni kiriting va USB qurilmangizdagi tugmani bosib roʻyxatga olinishingizni tasdiqlang.", ++ "yubi_otp": "Yubico OTP autentifikatsiya" ++ }, ++ "user": { ++ "action": "Amal", ++ "active": "Faol", ++ "active_sieve": "Faol filtr", ++ "advanced_settings": "Kengaytirilgan sozlamalar", ++ "alias": "Taxallus", ++ "alias_create_random": "Tasodifiy taxallus yaratish", ++ "alias_extend_all": "Taxalluslarni 1 soatga uzaytirish", ++ "alias_full_date": "d.m.Y, H:i:s T", ++ "alias_remove_all": "Barcha taxalluslarni olib tashlash", ++ "alias_select_validity": "Amal qilish muddati", ++ "alias_time_left": "Qolgan vaqt", ++ "alias_valid_until": "Amal qiladi (gacha)", ++ "aliases_also_send_as": "Foydalanuvchi sifatida ham joʻnatishga ruxsat berilgan", ++ "aliases_send_as_all": "Quyidagi domen(lar) va ularning taxallus domenlari uchun joʻnatuvchi kirishini tekshirmaslik", ++ "app_hint": "Ilova parollari sizning IMAP, SMTP, CalDAV, CardDAV va EAS kirishi uchun muqobil parollardir. Foydalanuvchi nomi oʻzgarmaydi. SOGo webmail ilova parollari orqali mavjud emas.", ++ "allowed_protocols": "Ruxsat etilgan protokollar", ++ "app_name": "Ilova nomi", ++ "app_passwds": "Ilova parollari", ++ "apple_connection_profile": "Apple ulanish profili", ++ "apple_connection_profile_complete": "Bu ulanish profili Apple qurilmasi uchun IMAP va SMTP parametrlari hamda CalDAV (kalendarlar) va CardDAV (kontaktlar) yoʻllarini oʻz ichiga oladi.", ++ "apple_connection_profile_mailonly": "Bu ulanish profili Apple qurilmasi uchun IMAP va SMTP konfiguratsiya parametrlarini oʻz ichiga oladi.", ++ "apple_connection_profile_with_app_password": "Yangi ilova paroli yaratiladi va profilga qoʻshiladi, shunda qurilmangizni sozlashda parol kiritish kerak boʻlmaydi. Iltimos, faylni ulashmang, chunki u pochta qutingizga toʻliq kirish huquqini beradi.", ++ "attribute": "Atribut", ++ "authentication": "Autentifikatsiya", ++ "change_password": "Parolni oʻzgartirish", ++ "change_password_hint_app_passwords": "Hisobingizda %d ta ilova paroli mavjud va ular oʻzgartirilmaydi. Ularni boshqarish uchun Ilova parollari yorligʻiga oʻting.", ++ "clear_recent_successful_connections": "Koʻrilgan muvaffaqiyatli ulanishlarni tozalash", ++ "client_configuration": "E-pochta mijozlari va smartfonlar uchun konfiguratsiya qoʻllanmalarini koʻrsatish", ++ "create_app_passwd": "Ilova paroli yaratish", ++ "create_syncjob": "Yangi sinxronizatsiya vazifasi yaratish", ++ "created_on": "Yaratilgan sana", ++ "daily": "Kunlik", ++ "day": "kun", ++ "description": "Tavsif", ++ "delete_ays": "Iltimos, oʻchirish jarayonini tasdiqlang.", ++ "direct_aliases": "Toʻgʻridan-toʻgʻri taxallus manzillari", ++ "direct_aliases_desc": "Toʻgʻridan-toʻgʻri taxallus manzillariga spam filtri va TLS siyosati sozlamalari taʼsir qiladi.", ++ "direct_protocol_access": "Bu pochta qutisi foydalanuvchisi quyidagi protokollar va ilovalarga toʻgʻridan-toʻgʻri, tashqi kirishga ega. Bu sozlama administratoringiz tomonidan boshqariladi. Maxsus protokollar va ilovalarga kirishga ruxsat berish uchun ilova parollarini yaratish mumkin.
\"Webmail\" tugmasi SOGo ga yagona kirish (SSO) imkonini beradi va doimo mavjud.", ++ "eas_reset": "ActiveSync qurilma keshini tiklash", ++ "eas_reset_help": "Koʻp hollarda qurilma keshini tiklash buzilgan ActiveSync profilini tiklashga yordam beradi.
Diqqat: Barcha elementlar qayta yuklab olinadi!", ++ "eas_reset_now": "Hozir tiklash", ++ "edit": "Tahrirlash", ++ "email": "E-pochta", ++ "email_and_dav": "E-pochta, kalendarlar va kontaktlar", ++ "empty": "Natijalar yoʻq", ++ "encryption": "Shifrlash", ++ "excludes": "Istisnolar", ++ "expire_in": "Tugaydi", ++ "expire_never": "Hech qachon tugamasin", ++ "fido2_webauthn": "FIDO2/WebAuthn", ++ "forever": "Abadiy", ++ "force_pw_update": "Guruh dasturi xizmatlariga kirish uchun siz yangi parol oʻrnatishingiz kerak.", ++ "from": "dan", ++ "generate": "yaratish", ++ "hour": "soat", ++ "hourly": "Soatlik", ++ "hours": "soat", ++ "in_use": "Foydalanilmoqda", ++ "interval": "Oraliq", ++ "is_catch_all": "Domen(lar) uchun Hammasini-qabul qilish", ++ "last_mail_login": "Oxirgi pochta kirishi", ++ "last_pw_change": "Oxirgi parol oʻzgarishi", ++ "last_run": "Oxirgi ishga tushirilgan", ++ "last_ui_login": "Oxirgi UI kirishi", ++ "loading": "Yuklanmoqda...", ++ "login_history": "Kirish tarixi", ++ "mailbox": "Pochta qutisi", ++ "mailbox_details": "Tafsilotlar", ++ "mailbox_general": "Umumiy", ++ "mailbox_settings": "Sozlamalar", ++ "messages": "xabarlar", ++ "month": "oy", ++ "months": "oy", ++ "never": "Hech qachon", ++ "new_password": "Yangi parol", ++ "new_password_repeat": "Tasdiqlash paroli (takrorlang)", ++ "no_active_filter": "Faol filtr mavjud emas", ++ "no_last_login": "Oxirgi UI kirishi haqida maʼlumot yoʻq", ++ "no_record": "Yozuv yoʻq", ++ "open_logs": "Jurnallarni ochish", ++ "open_webmail_sso": "Webmail", ++ "overview": "Umumiy koʻrinish", ++ "password": "Parol", ++ "password_now": "Joriy parol (oʻzgarishlarni tasdiqlang)", ++ "pw_update_required": "Hisobingiz parol oʻzgartirishni talab qiladi. Davom etish uchun yangi parolni oʻrnating.", ++ "password_repeat": "Parol (takrorlang)", ++ "password_reset_info": "Agar parolni tiklash uchun e-pochta kiritilmagan boʻlsa, bu funksiyadan foydalanib boʻlmaydi.", ++ "protocols": "Protokollar", ++ "pushover_evaluate_x_prio": "Yuqori muhimlikdagi xatni eskalatsiya qilish [X-Priority: 1]", ++ "pushover_info": "Push bildirishnoma sozlamalari %s ga taxalluslar bilan birga (umumiy, umumiy boʻlmagan, teglangan) yetkazib beriladigan barcha toza (spam boʻlmagan) xatlarga qoʻllaniladi.", ++ "pushover_only_x_prio": "Faqat yuqori muhimlikdagi xatlarni koʻrib chiqish [X-Priority: 1]", ++ "pushover_sender_array": "Quyidagi joʻnatuvchi e-pochta manzillarini koʻrib chiqish (vergul bilan ajratilgan)", ++ "pushover_sender_regex": "Joʻnatuvchilarni quyidagi regex orqali mos kelishini tekshirish", ++ "pushover_text": "Bildirishnoma matni", ++ "pushover_title": "Bildirishnoma sarlavhasi", ++ "pushover_sound": "Tovush", ++ "pushover_vars": "Joʻnatuvchi filtri belgilanmagan boʻlsa, barcha xatlar koʻrib chiqiladi.
Regex filtrlari va aniq joʻnatuvchi tekshiruvlari alohida belgilanishi mumkin va ketma-ket koʻrib chiqiladi. Ular bir-biriga bogʻliq emas.
Matn va sarlavha uchun ishlatiladigan oʻzgaruvchilar (ma'lumotlarni himoya qilish siyosatiga e'tibor bering)", ++ "pushover_verify": "Maʼlumotlarni tekshirish", ++ "pw_recovery_email": "Parolni tiklash e-pochtasi", ++ "q_add_header": "Junk papkasi", ++ "q_all": "Barcha turkumlar", ++ "q_reject": "Rad etilgan", ++ "quarantine_category": "Karantin bildirishnoma turkumi", ++ "quarantine_category_info": "\"Rad etilgan\" bildirishnoma turkumi rad etilgan xatlarni oʻz ichiga oladi, \"Junk papkasi\" esa Junk papkasiga joylashtirilgan xatlar haqida foydalanuvchini xabardor qiladi.", ++ "quarantine_notification": "Karantin bildirishnomalari", ++ "quarantine_notification_info": "Bildirishnoma yuborilgandan keyin elementlar \"xabar berildi\" deb belgilanadi va bu element uchun keyingi bildirishnomalar yuborilmaydi.", ++ "recent_successful_connections": "Koʻrilgan muvaffaqiyatli ulanishlar", ++ "remove": "Olib tashlash", ++ "running": "Ishlamoqda", ++ "save": "Oʻzgarishlarni saqlash", ++ "save_changes": "Oʻzgarishlarni saqlash", ++ "sender_acl_disabled": "Joʻnatuvchi tekshiruvi oʻchirilgan", ++ "shared_aliases": "Umumiy taxallus manzillari", ++ "shared_aliases_desc": "Umumiy taxalluslarga foydalanuvchining maxsus sozlamalari (spam filtri yoki shifrlash siyosati kabi) taʼsir qilmaydi. Mos spam filtrlarini faqat administrator domen boʻyicha siyosat sifatida sozlashi mumkin.", ++ "show_sieve_filters": "Faol foydalanuvchi sieve filtrini koʻrsatish", ++ "sogo_profile_reset": "SOGo profilini tiklash", ++ "sogo_profile_reset_help": "Bu foydalanuvchining SOGo profilini yoʻq qiladi va barcha kontakt va kalendar maʼlumotlarini qaytarib boʻlmas tarzda oʻchiradi.", ++ "sogo_profile_reset_now": "Profilni hozir tiklash", ++ "spam_aliases": "Spam e-pochta taxalluslari", ++ "spam_aliases_info": "Spam taxallusi — bu haqiqiy e-pochta manzillarini himoya qilish uchun ishlatilishi mumkin boʻlgan vaqtinchalik e-pochta manzilidir.
Ixtiyoriy ravishda muddat tugash vaqtini belgilash mumkin, shunda taxallus belgilangan davrdan keyin avtomatik oʻchirib qoʻyiladi, suiisteʼmol qilingan yoki tarqalib ketgan manzillarni samarali tarzda chiqarib tashlaydi.", ++ "spam_score_reset": "Server standartiga qaytarish", ++ "spamfilter": "Spam filtri", ++ "spamfilter_behavior": "Baholash", ++ "spamfilter_bl": "Qora roʻyxat", ++ "spamfilter_bl_desc": "Qora roʻyxatdagi e-pochta manzillari har doim spam sifatida tasniflanadi va rad etiladi. Rad etilgan xat karantinga nusxalanmaydi. Joker belgilar ishlatilishi mumkin. Filtr faqat toʻgʻridan-toʻgʻri taxalluslarga (bitta maqsad pochta qutisiga ega taxalluslarga) qoʻllaniladi, hammasini-qabul qilish taxalluslari va pochta qutisining oʻzi istisno qilinadi.", ++ "spamfilter_default_score": "Standart qiymatlar", ++ "spamfilter_green": "Yashil: bu xabar spam emas", ++ "spamfilter_hint": "Birinchi qiymat \"past spam bahosi\"ni tavsiflaydi, ikkinchisi \"yuqori spam bahosi\"ni ifodalaydi.", ++ "spamfilter_red": "Qizil: bu xabar spam va server tomonidan rad etiladi", ++ "spamfilter_table_action": "Amal", ++ "spamfilter_table_add": "Element qoʻshish", ++ "spamfilter_table_domain_policy": "n/a (domen siyosati)", ++ "spamfilter_table_empty": "Koʻrsatish uchun ma'lumot yoʻq", ++ "spamfilter_table_remove": "olib tashlash", ++ "spamfilter_table_rule": "Qoida", ++ "spamfilter_wl": "Oq roʻyxat", ++ "spamfilter_wl_desc": "Oq roʻyxatdagi e-pochta manzillari hech qachon spam sifatida tasniflanmaydi. Joker belgilar ishlatilishi mumkin. Filtr faqat toʻgʻridan-toʻgʻri taxalluslarga (bitta maqsad pochta qutisiga ega taxalluslarga) qoʻllaniladi, hammasini-qabul qilish taxalluslari va pochta qutisining oʻzi istisno qilinadi.", ++ "spamfilter_yellow": "Sariq: bu xabar spam boʻlishi mumkin, spam sifatida belgilanadi va Junk papkangizga koʻchiriladi", ++ "status": "Holat", ++ "sync_jobs": "Sinxronizatsiya vazifalari", ++ "syncjob_check_log": "Jurnalni tekshirish", ++ "syncjob_last_run_result": "Oxirgi ishga tushirilgan natija", ++ "syncjob_EX_OK": "Muvaffaqiyatli", ++ "syncjob_EXIT_CONNECTION_FAILURE": "Ulanish muammosi", ++ "syncjob_EXIT_TLS_FAILURE": "Shifrlangan ulanish bilan muammo", ++ "syncjob_EXIT_AUTHENTICATION_FAILURE": "Autentifikatsiya muammosi", ++ "syncjob_EXIT_OVERQUOTA": "Maqsad pochta qutisi kvotadan oshib ketdi", ++ "syncjob_EXIT_CONNECTION_FAILURE_HOST1": "Masofaviy serverga ulanib boʻlmadi", ++ "syncjob_EXIT_AUTHENTICATION_FAILURE_USER1": "Notoʻgʻri foydalanuvchi nomi yoki parol", ++ "tag_handling": "Teglangan xat uchun ishlovni oʻrnatish", ++ "tag_help_example": "Teglangan e-pochta manzili misoli: me+Facebook@example.org", ++ "tag_help_explain": "Subpapkada: tegga qarab nomlangan yangi subpapka INBOX ostida yaratiladi (\"INBOX/Facebook\").
\r\nMavzuda: teg nomi xatning mavzusiga oldindan qoʻshiladi, misol: \"[Facebook] Mening yangiliklarim\".", ++ "tag_in_none": "Hech narsa qilmaslik", ++ "tag_in_subfolder": "Subpapkada", ++ "tag_in_subject": "Mavzuda", ++ "text": "Matn", ++ "tfa_info": "Ikki faktorli autentifikatsiya hisobingizni himoya qilishga yordam beradi. Uni yoqsangiz, ikki faktorli autentifikatsiyani qoʻllab-quvvatlamaydigan ilovalar yoki xizmatlarga (masalan, pochta mijozlari) kirish uchun ilova parollari kerak boʻladi.", ++ "title": "Sarlavha", ++ "tls_enforce_in": "Kiruvchi TLS ni majburlash", ++ "tls_enforce_out": "Chiquvchi TLS ni majburlash", ++ "tls_policy": "Shifrlash siyosati", ++ "tls_policy_warning": "Diqqat: Agar shifrlangan pochta transferini majburlashga qaror qilsangiz, e-pochtalarni yoʻqotishingiz mumkin.
Siyosatga mos kelmaydigan xabarlar pochta tizimi tomonidan qatʼiy muvaffaqiyatsizlik bilan qaytariladi.
Bu variant sizning asosiy e-pochta manzilingiz (kirish nomingiz), taxallus domenlaridan olingan barcha manzillar va faqat ushbu pochta qutisi maqsad sifatida boʻlgan taxallus manzillariga qoʻllaniladi.", ++ "user_settings": "Foydalanuvchi sozlamalari", ++ "username": "Foydalanuvchi nomi", ++ "value": "Qiymat", ++ "verify": "Tasdiqlash", ++ "waiting": "Kutilmoqda", ++ "week": "hafta", ++ "weekly": "Haftalik", ++ "weeks": "hafta", ++ "with_app_password": "ilova paroli bilan", ++ "year": "yil", ++ "years": "yil" ++ }, ++ "warning": { ++ "cannot_delete_self": "Tizimga kirgan foydalanuvchini oʻchirib boʻlmaydi", ++ "domain_added_sogo_failed": "Domen qoʻshildi, ammo SOGoni qayta ishga tushirib boʻlmadi, iltimos server jurnallaringizni tekshiring.", ++ "dovecot_restart_failed": "Dovecot qayta ishga tushirib boʻlmadi, iltimos jurnallarni tekshiring", ++ "fuzzy_learn_error": "Fuzzy hash oʻrgatish xatosi: %s", ++ "hash_not_found": "Hash topilmadi yoki allaqachon oʻchirilgan", ++ "ip_invalid": "Notoʻgʻri IP oʻtkazib yuborildi: %s", ++ "is_not_primary_alias": "Asosiy boʻlmagan taxallus oʻtkazib yuborildi: %s", ++ "no_active_admin": "Oxirgi faol administratorni oʻchirib boʻlmaydi", ++ "quota_exceeded_scope": "Domen kvotasi oshib ketdi: Bu domen doirasida faqat cheksiz pochta qutilari yaratilishi mumkin.", ++ "session_token": "Forma tokeni noto'g'ri: Token mos kelmadi", ++ "session_ua": "Forma tokeni noto'g'ri: User-Agent tekshiruvi xatosi" ++ } ++} diff --git a/tasks/mailcow__mailcow-dockerized-7224/tests/test.sh b/tasks/mailcow__mailcow-dockerized-7224/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..e05ea56d54edd54a80b2a9b79ba1660130063fd6 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7224/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace a8e945f3da89b98258a01b5137ca1a9dc72d67d9 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "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-7224/tests/verifier.py b/tasks/mailcow__mailcow-dockerized-7224/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7224/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "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-7226/environment/Dockerfile b/tasks/mailcow__mailcow-dockerized-7226/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..17ae27d505d1ebc430dcb3f71d3a5199b85490f2 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7226/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git 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 a8e945f3da89b98258a01b5137ca1a9dc72d67d9 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard a8e945f3da89b98258a01b5137ca1a9dc72d67d9 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base a8e945f3da89b98258a01b5137ca1a9dc72d67d9 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -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-7226/instruction.md b/tasks/mailcow__mailcow-dockerized-7226/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..cbdf9cd61c56eb6233e2cca4bb1263e1fd85eee3 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7226/instruction.md @@ -0,0 +1,47 @@ +# Issue + +**Title:** [SOGo] Update to 5.12.8 + +## 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 + +Updates SOGo to 5.12.8, including 4 security fixes. +https://www.sogo.nu/news/2026/sogo-v5128-released.html + +### Affected Containers + + + + + +- sogo-mailcow + +## Did you run tests? + +### What did you tested? + +Verified that SOGo was updated to version 5.12.8 successfully. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `a8e945f3da89`. Edit files in place; the verifier captures your changes via `git diff` 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-7226/solution/patch.diff b/tasks/mailcow__mailcow-dockerized-7226/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..faf23ed09b449c3cfe629266686e8f699736f054 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7226/solution/patch.diff @@ -0,0 +1,36 @@ +diff --git a/data/Dockerfiles/sogo/Dockerfile b/data/Dockerfiles/sogo/Dockerfile +index 96d2e0a4..1c728720 100644 +--- a/data/Dockerfiles/sogo/Dockerfile ++++ b/data/Dockerfiles/sogo/Dockerfile +@@ -1,6 +1,6 @@ + # SOGo built from source to enable security patch application + # Repository: https://github.com/Alinto/sogo +-# Version: SOGo-5.12.4 ++# Version: SOGo-5.12.8 + # + # Applied security patches: + # - +@@ -12,8 +12,8 @@ FROM debian:bookworm + LABEL maintainer="The Infrastructure Company GmbH " + + ARG DEBIAN_FRONTEND=noninteractive +-ARG SOGO_VERSION=SOGo-5.12.5 +-ARG SOPE_VERSION=SOPE-5.12.5 ++ARG SOGO_VERSION=SOGo-5.12.8 ++ARG SOPE_VERSION=SOPE-5.12.8 + # Security patches to apply (space-separated commit hashes) + ARG SOGO_SECURITY_PATCHES="" + # renovate: datasource=github-releases depName=tianon/gosu versioning=semver-coerced extractVersion=^(?.*)$ +diff --git a/docker-compose.yml b/docker-compose.yml +index 0a9578de..90e5518d 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-3 ++ image: ghcr.io/mailcow/sogo:5.12.8-1 + environment: + - DBNAME=${DBNAME} + - DBUSER=${DBUSER} diff --git a/tasks/mailcow__mailcow-dockerized-7226/solution/solve.sh b/tasks/mailcow__mailcow-dockerized-7226/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7226/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo 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-7226/task.toml b/tasks/mailcow__mailcow-dockerized-7226/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9fe205504d80b1aa2f24cde9034e5a35ffde9d4e --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7226/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/mailcow__mailcow-dockerized-7226" +description = "[SOGo] Update to 5.12.8" + +[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 = "a8e945f3da89b98258a01b5137ca1a9dc72d67d9" +reference = "https://github.com/mailcow/mailcow-dockerized/pull/7226" +source_access = "auto" +built_at = "2026-11-16T16:09:53.195143+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:a39ab55ca7f8f2760ed5a7d3dce05fc524a7ef7ead01e63d0d81d5318a47074f" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-05-13T08:34: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 = 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.451998+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:db4f23a1d1b82ab4b5a81ab2b1ee2d8f4f71c9144aaf4dc836db5bccd712fcb8" +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-7226/tests/capture.py b/tasks/mailcow__mailcow-dockerized-7226/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7226/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture 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-7226/tests/instruction.md b/tasks/mailcow__mailcow-dockerized-7226/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..cbdf9cd61c56eb6233e2cca4bb1263e1fd85eee3 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7226/tests/instruction.md @@ -0,0 +1,47 @@ +# Issue + +**Title:** [SOGo] Update to 5.12.8 + +## 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 + +Updates SOGo to 5.12.8, including 4 security fixes. +https://www.sogo.nu/news/2026/sogo-v5128-released.html + +### Affected Containers + + + + + +- sogo-mailcow + +## Did you run tests? + +### What did you tested? + +Verified that SOGo was updated to version 5.12.8 successfully. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `a8e945f3da89`. Edit files in place; the verifier captures your changes via `git diff` 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-7226/tests/oracle.patch b/tasks/mailcow__mailcow-dockerized-7226/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..faf23ed09b449c3cfe629266686e8f699736f054 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7226/tests/oracle.patch @@ -0,0 +1,36 @@ +diff --git a/data/Dockerfiles/sogo/Dockerfile b/data/Dockerfiles/sogo/Dockerfile +index 96d2e0a4..1c728720 100644 +--- a/data/Dockerfiles/sogo/Dockerfile ++++ b/data/Dockerfiles/sogo/Dockerfile +@@ -1,6 +1,6 @@ + # SOGo built from source to enable security patch application + # Repository: https://github.com/Alinto/sogo +-# Version: SOGo-5.12.4 ++# Version: SOGo-5.12.8 + # + # Applied security patches: + # - +@@ -12,8 +12,8 @@ FROM debian:bookworm + LABEL maintainer="The Infrastructure Company GmbH " + + ARG DEBIAN_FRONTEND=noninteractive +-ARG SOGO_VERSION=SOGo-5.12.5 +-ARG SOPE_VERSION=SOPE-5.12.5 ++ARG SOGO_VERSION=SOGo-5.12.8 ++ARG SOPE_VERSION=SOPE-5.12.8 + # Security patches to apply (space-separated commit hashes) + ARG SOGO_SECURITY_PATCHES="" + # renovate: datasource=github-releases depName=tianon/gosu versioning=semver-coerced extractVersion=^(?.*)$ +diff --git a/docker-compose.yml b/docker-compose.yml +index 0a9578de..90e5518d 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-3 ++ image: ghcr.io/mailcow/sogo:5.12.8-1 + environment: + - DBNAME=${DBNAME} + - DBUSER=${DBUSER} diff --git a/tasks/mailcow__mailcow-dockerized-7226/tests/test.sh b/tasks/mailcow__mailcow-dockerized-7226/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..e05ea56d54edd54a80b2a9b79ba1660130063fd6 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7226/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace a8e945f3da89b98258a01b5137ca1a9dc72d67d9 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "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-7226/tests/verifier.py b/tasks/mailcow__mailcow-dockerized-7226/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7226/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "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-7227/environment/Dockerfile b/tasks/mailcow__mailcow-dockerized-7227/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..23c2ebb5908a8ecb38b020a0e168485dbfad37f1 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7227/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git 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 32156a337a8a531ae0b43012c2367b91289f309f 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 32156a337a8a531ae0b43012c2367b91289f309f \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 32156a337a8a531ae0b43012c2367b91289f309f \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -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-7227/instruction.md b/tasks/mailcow__mailcow-dockerized-7227/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..86ac4b20299b51b709bcda436b63ff6d39dffea3 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7227/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Update 2026-05a + +## Description + +Update 2026-05a + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `32156a337a8a`. Edit files in place; the verifier captures your changes via `git diff` 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-7227/solution/patch.diff b/tasks/mailcow__mailcow-dockerized-7227/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..faf23ed09b449c3cfe629266686e8f699736f054 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7227/solution/patch.diff @@ -0,0 +1,36 @@ +diff --git a/data/Dockerfiles/sogo/Dockerfile b/data/Dockerfiles/sogo/Dockerfile +index 96d2e0a4..1c728720 100644 +--- a/data/Dockerfiles/sogo/Dockerfile ++++ b/data/Dockerfiles/sogo/Dockerfile +@@ -1,6 +1,6 @@ + # SOGo built from source to enable security patch application + # Repository: https://github.com/Alinto/sogo +-# Version: SOGo-5.12.4 ++# Version: SOGo-5.12.8 + # + # Applied security patches: + # - +@@ -12,8 +12,8 @@ FROM debian:bookworm + LABEL maintainer="The Infrastructure Company GmbH " + + ARG DEBIAN_FRONTEND=noninteractive +-ARG SOGO_VERSION=SOGo-5.12.5 +-ARG SOPE_VERSION=SOPE-5.12.5 ++ARG SOGO_VERSION=SOGo-5.12.8 ++ARG SOPE_VERSION=SOPE-5.12.8 + # Security patches to apply (space-separated commit hashes) + ARG SOGO_SECURITY_PATCHES="" + # renovate: datasource=github-releases depName=tianon/gosu versioning=semver-coerced extractVersion=^(?.*)$ +diff --git a/docker-compose.yml b/docker-compose.yml +index 0a9578de..90e5518d 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-3 ++ image: ghcr.io/mailcow/sogo:5.12.8-1 + environment: + - DBNAME=${DBNAME} + - DBUSER=${DBUSER} diff --git a/tasks/mailcow__mailcow-dockerized-7227/solution/solve.sh b/tasks/mailcow__mailcow-dockerized-7227/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7227/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo 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-7227/task.toml b/tasks/mailcow__mailcow-dockerized-7227/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..6db0f25808aeb66071bd6d7cf091dd4111910b96 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7227/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/mailcow__mailcow-dockerized-7227" +description = "Update 2026-05a" + +[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 = "32156a337a8a531ae0b43012c2367b91289f309f" +reference = "https://github.com/mailcow/mailcow-dockerized/pull/7227" +source_access = "auto" +built_at = "2026-11-16T16:09:53.204611+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:18e8d5022eff7e6c64e94556e5dfbcdce4f3904c3d4a6b5dbe9656739b86027b" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-05-13T08:42:14Z" +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.452505+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:c53be2c48669e6fe9805625a1770be798a4132b556c909ee3b80ecc33bd4c316" +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-7227/tests/capture.py b/tasks/mailcow__mailcow-dockerized-7227/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7227/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture 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-7227/tests/instruction.md b/tasks/mailcow__mailcow-dockerized-7227/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..86ac4b20299b51b709bcda436b63ff6d39dffea3 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7227/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Update 2026-05a + +## Description + +Update 2026-05a + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `32156a337a8a`. Edit files in place; the verifier captures your changes via `git diff` 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-7227/tests/oracle.patch b/tasks/mailcow__mailcow-dockerized-7227/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..faf23ed09b449c3cfe629266686e8f699736f054 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7227/tests/oracle.patch @@ -0,0 +1,36 @@ +diff --git a/data/Dockerfiles/sogo/Dockerfile b/data/Dockerfiles/sogo/Dockerfile +index 96d2e0a4..1c728720 100644 +--- a/data/Dockerfiles/sogo/Dockerfile ++++ b/data/Dockerfiles/sogo/Dockerfile +@@ -1,6 +1,6 @@ + # SOGo built from source to enable security patch application + # Repository: https://github.com/Alinto/sogo +-# Version: SOGo-5.12.4 ++# Version: SOGo-5.12.8 + # + # Applied security patches: + # - +@@ -12,8 +12,8 @@ FROM debian:bookworm + LABEL maintainer="The Infrastructure Company GmbH " + + ARG DEBIAN_FRONTEND=noninteractive +-ARG SOGO_VERSION=SOGo-5.12.5 +-ARG SOPE_VERSION=SOPE-5.12.5 ++ARG SOGO_VERSION=SOGo-5.12.8 ++ARG SOPE_VERSION=SOPE-5.12.8 + # Security patches to apply (space-separated commit hashes) + ARG SOGO_SECURITY_PATCHES="" + # renovate: datasource=github-releases depName=tianon/gosu versioning=semver-coerced extractVersion=^(?.*)$ +diff --git a/docker-compose.yml b/docker-compose.yml +index 0a9578de..90e5518d 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-3 ++ image: ghcr.io/mailcow/sogo:5.12.8-1 + environment: + - DBNAME=${DBNAME} + - DBUSER=${DBUSER} diff --git a/tasks/mailcow__mailcow-dockerized-7227/tests/test.sh b/tasks/mailcow__mailcow-dockerized-7227/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..d9148af34815747d6d66636ebc797a0341cb2feb --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7227/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 32156a337a8a531ae0b43012c2367b91289f309f > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "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-7227/tests/verifier.py b/tasks/mailcow__mailcow-dockerized-7227/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7227/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "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-7228/environment/Dockerfile b/tasks/mailcow__mailcow-dockerized-7228/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..02c49f19fb671a43b176a2a931bec1625b2881b4 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7228/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git 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 9175e5f0865e60668f72db73c1752fa183e84457 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 9175e5f0865e60668f72db73c1752fa183e84457 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 9175e5f0865e60668f72db73c1752fa183e84457 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -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-7228/instruction.md b/tasks/mailcow__mailcow-dockerized-7228/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..eda4337f3c4ecc1ba5079890aa99a46236c25f93 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7228/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 `9175e5f0865e`. Edit files in place; the verifier captures your changes via `git diff` 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-7228/solution/patch.diff b/tasks/mailcow__mailcow-dockerized-7228/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..fe509a3cfded55c0284879210e495c7b7d8883db --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7228/solution/patch.diff @@ -0,0 +1,76 @@ +diff --git a/data/web/lang/lang.pt-br.json b/data/web/lang/lang.pt-br.json +index 24105db1..db3c8cac 100644 +--- a/data/web/lang/lang.pt-br.json ++++ b/data/web/lang/lang.pt-br.json +@@ -38,7 +38,7 @@ + "add_domain_only": "Adicionar somente domínio", + "add_domain_restart": "Adicionar domínio e reiniciar o SoGo", + "alias_address": "Endereço (s) de alias", +- "alias_address_info": "Endereço/s de e-mail completo ou @example .com, para capturar todas as mensagens de um domínio (separadas por vírgula). somente domínios mailcow.", ++ "alias_address_info": "Endereço(s) de e-mail completo(s) ou @example.com, para capturar todas as mensagens de um domínio (separadas por vírgula). Apenas domínios do Mailcow.", + "alias_domain": "Domínio de alias", + "alias_domain_info": "Somente nomes de domínio válidos (separados por vírgula).", + "app_name": "Nome do aplicativo", +@@ -158,7 +158,7 @@ + "logo_dark_label": "Invertido para o modo escuro", + "configuration": "Configuração", + "convert_html_to_text": "Converter HTML em texto sem formatação", +- "copy_to_clipboard": "Text copied to clipboard!", ++ "copy_to_clipboard": "Copiado para a área de transferência!", + "cors_settings": "Configurações do CORS", + "credentials_transport_warning": "Aviso: Adicionar uma nova entrada no mapa de transporte atualizará as credenciais de todas as entradas com uma coluna correspondente do próximo salto.", + "customer_id": "ID do cliente", +@@ -223,7 +223,7 @@ + "includes": "Inclua esses destinatários", + "ip_check": "Verificação de IP", + "ip_check_disabled": "A verificação de IP está desativada. Você pode ativá-lo em
Sistema > Configuração > Opções > Personalizar", +- "ip_check_opt_in": "Opte por usar o serviço de terceiros ipv4.mailcow.email. e ipv6.mailcow.email para resolver endereços IP externos.", ++ "ip_check_opt_in": "Opte por usar o serviço de terceiros ipv4.mailcow.email e ipv6.mailcow.email para resolver endereços IP externos.", + "is_mx_based": "Baseado em MX", + "last_applied": "Aplicado pela última vez", + "license_info": "Uma licença não é necessária, mas ajuda no desenvolvimento.
Registre seu GUID aqui ou comprar suporte para sua instalação de mailcow.", +@@ -245,7 +245,7 @@ + "oauth2_add_client": "Adicionar cliente OAuth2", + "oauth2_client_id": "ID do cliente", + "oauth2_client_secret": "Segredo do cliente", +- "oauth2_info": "A implementação OAuth2 suporta o tipo de concessão \"Código de Autorização\" e emite tokens de atualização.
\nO servidor também emite automaticamente novos tokens de atualização, depois que um token de atualização foi usado.

\n• O escopo padrão é perfil. Somente usuários com caixa de e-mail podem ser autenticados contra o OAuth2. Se o parâmetro de escopo for omitido, ele voltará para perfil.
\nCaminhos para solicitações OAuth2 API:
\n
    \n
  • Endpoint de autorização: /oauth/authorize
  • \n
  • Endpoint token: /oauth/token
  • \n
  • Página de recursos: /oauth/profile
  • \n
\nRegenerar o segredo do cliente não expirará os códigos de autorização existentes, mas eles não renovarão seu token.

\nA revogação dos tokens do cliente causará o término imediato de todas as sessões ativas. Todos os clientes precisam se autenticar novamente.", ++ "oauth2_info": "A implementação do OAuth2 suporta o tipo de concessão \"Código de Autorização\" e emite tokens de atualização.
\nO servidor também emite automaticamente novos tokens de atualização após um token de atualização ter sido usado.
\nO escopo padrão é profile. Somente usuários de caixa de correio podem ser autenticados com o OAuth2. Se o parâmetro de escopo for omitido, o padrão será profile.
\nO parâmetro state deve ser enviado pelo cliente como parte da solicitação de autorização.

\nCaminhos para solicitações à API OAuth2:
\n\n
    \n
  • Ponto de extremidade de autorização: /oauth/authorize
  • \n
  • Endpoint do token: /oauth/token
  • \n
  • Página de recursos: /oauth/profile
  • \n
\n\nRegenerar o segredo do cliente não expirará os códigos de autorização existentes, mas impedirá a renovação do token.

\nA revogação dos tokens de cliente causará o encerramento imediato de todas as sessões ativas. Todos os clientes precisarão se autenticar novamente.", + "oauth2_redirect_uri": "URI de redirecionamento", + "oauth2_renew_secret": "Gere um novo segredo de cliente", + "oauth2_revoke_tokens": "Revogar todos os tokens do cliente", +@@ -730,7 +730,7 @@ + "pushover_verify": "Verifique as credenciais", + "quota_mb": "Cota (MiB)", + "quota_warning_bcc": "Aviso de cota BCC", +- "quota_warning_bcc_info": "Os avisos serão enviados em cópias separadas para os seguintes destinatários. O assunto será sufixado pelo nome de usuário correspondente entre colchetes, por exemplo: Aviso de cota (user@example.com).", ++ "quota_warning_bcc_info": "Os avisos serão enviados em cópias separadas para os seguintes destinatários. O assunto será precedido pelo nome de usuário correspondente entre colchetes, por exemplo: Aviso de cota (user@example.com).", + "ratelimit": "Limite de taxa", + "redirect_uri": "URL de redirecionamento/retorno de chamada", + "relay_all": "Retransmita todos os destinatários", +@@ -759,7 +759,7 @@ + "spam_score": "Defina uma pontuação de spam personalizada", + "subfolder2": "Sincronizar na subpasta no destino
(vazio = não usar subpasta)", + "syncjob": "Editar tarefa de sincronização", +- "target_address": "Ir para endereço/es (separados por vírgula)", ++ "target_address": "Ir para o(s) endereço(s) (separados por vírgula)", + "target_domain": "Domínio de destino", + "timeout1": "Tempo limite para conexão com o host remoto", + "timeout2": "Tempo limite para conexão com o host local", +@@ -807,7 +807,7 @@ + "cancel": "Cancelar", + "confirm_delete": "Confirme a exclusão", + "delete_now": "Excluir agora", +- "delete_these_items": "Confirme suas alterações no seguinte ID de objeto", ++ "delete_these_items": "Por favor, confirme as alterações feitas no seguinte ID de objeto.", + "hibp_check": "Verifique em haveibeenpwned.com", + "hibp_nok": "Combinado! Essa é uma senha potencialmente perigosa!", + "hibp_ok": "Nenhuma combinação encontrada.", +@@ -1393,7 +1393,7 @@ + "syncjob_EXIT_CONNECTION_FAILURE_HOST1": "Não é possível se conectar ao servidor remoto", + "syncjob_EXIT_AUTHENTICATION_FAILURE_USER1": "Nome de usuário ou senha incorretos", + "tag_handling": "Definir o tratamento para e-mails marcados", +- "tag_help_example": "Exemplo de um endereço de e-mail marcado: me +Facebook @example .org", ++ "tag_help_example": "Exemplo de endereço de e-mail com tag: eu+Facebook
@exemplo.org", + "tag_help_explain": "Na subpasta: uma nova subpasta com o nome da tag será criada abaixo da CAIXA DE ENTRADA (“Caixa de entrada/Facebook”).
\r\nNo assunto: o nome das tags será anexado ao assunto do e-mail, por exemplo: “[Facebook] Minhas notícias”.", + "tag_in_none": "Não faça nada", + "tag_in_subfolder": "Na subpasta", diff --git a/tasks/mailcow__mailcow-dockerized-7228/solution/solve.sh b/tasks/mailcow__mailcow-dockerized-7228/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7228/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo 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-7228/task.toml b/tasks/mailcow__mailcow-dockerized-7228/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..751b82d3ebb64966452226627dde50c346458ac2 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7228/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/mailcow__mailcow-dockerized-7228" +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 = "9175e5f0865e60668f72db73c1752fa183e84457" +reference = "https://github.com/mailcow/mailcow-dockerized/pull/7228" +source_access = "auto" +built_at = "2026-11-16T16:09:53.203233+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:0355b291b87108575d2844fd87d94c9afd06317fb31ecf090dd732f61be17775" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-05-13T14:42:03Z" +diff_format = "unified" +context_files = [ + "data/web/lang/lang.pt-br.json", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 16 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.453010+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:9a2058b9e4c2e2b4866480e2740c42eb353d870a537c29eed05095f3da756ac0" +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-7228/tests/capture.py b/tasks/mailcow__mailcow-dockerized-7228/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7228/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture 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-7228/tests/instruction.md b/tasks/mailcow__mailcow-dockerized-7228/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..eda4337f3c4ecc1ba5079890aa99a46236c25f93 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7228/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 `9175e5f0865e`. Edit files in place; the verifier captures your changes via `git diff` 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-7228/tests/oracle.patch b/tasks/mailcow__mailcow-dockerized-7228/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..fe509a3cfded55c0284879210e495c7b7d8883db --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7228/tests/oracle.patch @@ -0,0 +1,76 @@ +diff --git a/data/web/lang/lang.pt-br.json b/data/web/lang/lang.pt-br.json +index 24105db1..db3c8cac 100644 +--- a/data/web/lang/lang.pt-br.json ++++ b/data/web/lang/lang.pt-br.json +@@ -38,7 +38,7 @@ + "add_domain_only": "Adicionar somente domínio", + "add_domain_restart": "Adicionar domínio e reiniciar o SoGo", + "alias_address": "Endereço (s) de alias", +- "alias_address_info": "Endereço/s de e-mail completo ou @example .com, para capturar todas as mensagens de um domínio (separadas por vírgula). somente domínios mailcow.", ++ "alias_address_info": "Endereço(s) de e-mail completo(s) ou @example.com, para capturar todas as mensagens de um domínio (separadas por vírgula). Apenas domínios do Mailcow.", + "alias_domain": "Domínio de alias", + "alias_domain_info": "Somente nomes de domínio válidos (separados por vírgula).", + "app_name": "Nome do aplicativo", +@@ -158,7 +158,7 @@ + "logo_dark_label": "Invertido para o modo escuro", + "configuration": "Configuração", + "convert_html_to_text": "Converter HTML em texto sem formatação", +- "copy_to_clipboard": "Text copied to clipboard!", ++ "copy_to_clipboard": "Copiado para a área de transferência!", + "cors_settings": "Configurações do CORS", + "credentials_transport_warning": "Aviso: Adicionar uma nova entrada no mapa de transporte atualizará as credenciais de todas as entradas com uma coluna correspondente do próximo salto.", + "customer_id": "ID do cliente", +@@ -223,7 +223,7 @@ + "includes": "Inclua esses destinatários", + "ip_check": "Verificação de IP", + "ip_check_disabled": "A verificação de IP está desativada. Você pode ativá-lo em
Sistema > Configuração > Opções > Personalizar", +- "ip_check_opt_in": "Opte por usar o serviço de terceiros ipv4.mailcow.email. e ipv6.mailcow.email para resolver endereços IP externos.", ++ "ip_check_opt_in": "Opte por usar o serviço de terceiros ipv4.mailcow.email e ipv6.mailcow.email para resolver endereços IP externos.", + "is_mx_based": "Baseado em MX", + "last_applied": "Aplicado pela última vez", + "license_info": "Uma licença não é necessária, mas ajuda no desenvolvimento.
Registre seu GUID aqui ou comprar suporte para sua instalação de mailcow.", +@@ -245,7 +245,7 @@ + "oauth2_add_client": "Adicionar cliente OAuth2", + "oauth2_client_id": "ID do cliente", + "oauth2_client_secret": "Segredo do cliente", +- "oauth2_info": "A implementação OAuth2 suporta o tipo de concessão \"Código de Autorização\" e emite tokens de atualização.
\nO servidor também emite automaticamente novos tokens de atualização, depois que um token de atualização foi usado.

\n• O escopo padrão é perfil. Somente usuários com caixa de e-mail podem ser autenticados contra o OAuth2. Se o parâmetro de escopo for omitido, ele voltará para perfil.
\nCaminhos para solicitações OAuth2 API:
\n
    \n
  • Endpoint de autorização: /oauth/authorize
  • \n
  • Endpoint token: /oauth/token
  • \n
  • Página de recursos: /oauth/profile
  • \n
\nRegenerar o segredo do cliente não expirará os códigos de autorização existentes, mas eles não renovarão seu token.

\nA revogação dos tokens do cliente causará o término imediato de todas as sessões ativas. Todos os clientes precisam se autenticar novamente.", ++ "oauth2_info": "A implementação do OAuth2 suporta o tipo de concessão \"Código de Autorização\" e emite tokens de atualização.
\nO servidor também emite automaticamente novos tokens de atualização após um token de atualização ter sido usado.
\nO escopo padrão é profile. Somente usuários de caixa de correio podem ser autenticados com o OAuth2. Se o parâmetro de escopo for omitido, o padrão será profile.
\nO parâmetro state deve ser enviado pelo cliente como parte da solicitação de autorização.

\nCaminhos para solicitações à API OAuth2:
\n\n
    \n
  • Ponto de extremidade de autorização: /oauth/authorize
  • \n
  • Endpoint do token: /oauth/token
  • \n
  • Página de recursos: /oauth/profile
  • \n
\n\nRegenerar o segredo do cliente não expirará os códigos de autorização existentes, mas impedirá a renovação do token.

\nA revogação dos tokens de cliente causará o encerramento imediato de todas as sessões ativas. Todos os clientes precisarão se autenticar novamente.", + "oauth2_redirect_uri": "URI de redirecionamento", + "oauth2_renew_secret": "Gere um novo segredo de cliente", + "oauth2_revoke_tokens": "Revogar todos os tokens do cliente", +@@ -730,7 +730,7 @@ + "pushover_verify": "Verifique as credenciais", + "quota_mb": "Cota (MiB)", + "quota_warning_bcc": "Aviso de cota BCC", +- "quota_warning_bcc_info": "Os avisos serão enviados em cópias separadas para os seguintes destinatários. O assunto será sufixado pelo nome de usuário correspondente entre colchetes, por exemplo: Aviso de cota (user@example.com).", ++ "quota_warning_bcc_info": "Os avisos serão enviados em cópias separadas para os seguintes destinatários. O assunto será precedido pelo nome de usuário correspondente entre colchetes, por exemplo: Aviso de cota (user@example.com).", + "ratelimit": "Limite de taxa", + "redirect_uri": "URL de redirecionamento/retorno de chamada", + "relay_all": "Retransmita todos os destinatários", +@@ -759,7 +759,7 @@ + "spam_score": "Defina uma pontuação de spam personalizada", + "subfolder2": "Sincronizar na subpasta no destino
(vazio = não usar subpasta)", + "syncjob": "Editar tarefa de sincronização", +- "target_address": "Ir para endereço/es (separados por vírgula)", ++ "target_address": "Ir para o(s) endereço(s) (separados por vírgula)", + "target_domain": "Domínio de destino", + "timeout1": "Tempo limite para conexão com o host remoto", + "timeout2": "Tempo limite para conexão com o host local", +@@ -807,7 +807,7 @@ + "cancel": "Cancelar", + "confirm_delete": "Confirme a exclusão", + "delete_now": "Excluir agora", +- "delete_these_items": "Confirme suas alterações no seguinte ID de objeto", ++ "delete_these_items": "Por favor, confirme as alterações feitas no seguinte ID de objeto.", + "hibp_check": "Verifique em haveibeenpwned.com", + "hibp_nok": "Combinado! Essa é uma senha potencialmente perigosa!", + "hibp_ok": "Nenhuma combinação encontrada.", +@@ -1393,7 +1393,7 @@ + "syncjob_EXIT_CONNECTION_FAILURE_HOST1": "Não é possível se conectar ao servidor remoto", + "syncjob_EXIT_AUTHENTICATION_FAILURE_USER1": "Nome de usuário ou senha incorretos", + "tag_handling": "Definir o tratamento para e-mails marcados", +- "tag_help_example": "Exemplo de um endereço de e-mail marcado: me +Facebook @example .org", ++ "tag_help_example": "Exemplo de endereço de e-mail com tag: eu+Facebook
@exemplo.org", + "tag_help_explain": "Na subpasta: uma nova subpasta com o nome da tag será criada abaixo da CAIXA DE ENTRADA (“Caixa de entrada/Facebook”).
\r\nNo assunto: o nome das tags será anexado ao assunto do e-mail, por exemplo: “[Facebook] Minhas notícias”.", + "tag_in_none": "Não faça nada", + "tag_in_subfolder": "Na subpasta", diff --git a/tasks/mailcow__mailcow-dockerized-7228/tests/test.sh b/tasks/mailcow__mailcow-dockerized-7228/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..622b53dce2ca9f8c22d3a8b9e3e2870b31de5de7 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7228/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 9175e5f0865e60668f72db73c1752fa183e84457 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "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-7228/tests/verifier.py b/tasks/mailcow__mailcow-dockerized-7228/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7228/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "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-7240/environment/Dockerfile b/tasks/mailcow__mailcow-dockerized-7240/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b44daa27a90bf0ec00297ad8548d3fbaf64e0b86 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7240/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git 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 07373907e3722fe15d31e68d93a281f92d344400 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 07373907e3722fe15d31e68d93a281f92d344400 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 07373907e3722fe15d31e68d93a281f92d344400 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -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-7240/instruction.md b/tasks/mailcow__mailcow-dockerized-7240/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6fc1550f0115fcb6bac5d765b43818b7c327074b --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7240/instruction.md @@ -0,0 +1,30 @@ +# Issue + +**Title:** [Nginx] Update to 1.30.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 + +Pin nginx base image to `1.30.1-alpine`. + +### Affected Containers + +- nginx-mailcow + +## Did you run tests? + +### What did you tested? + +Built and started the container, verified `nginx -v` reports 1.30.1, +checked web UI and SOGo. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `07373907e372`. Edit files in place; the verifier captures your changes via `git diff` 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-7240/solution/patch.diff b/tasks/mailcow__mailcow-dockerized-7240/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..5136e78645b8c7605c9d6e0ed9168d5a411fe3c4 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7240/solution/patch.diff @@ -0,0 +1,23 @@ +diff --git a/data/Dockerfiles/nginx/Dockerfile b/data/Dockerfiles/nginx/Dockerfile +index 7d2ce34f..b8746684 100644 +--- a/data/Dockerfiles/nginx/Dockerfile ++++ b/data/Dockerfiles/nginx/Dockerfile +@@ -1,4 +1,4 @@ +-FROM nginx:alpine ++FROM nginx:1.30.1-alpine + LABEL maintainer "The Infrastructure Company GmbH " + + ENV PIP_BREAK_SYSTEM_PACKAGES=1 +diff --git a/docker-compose.yml b/docker-compose.yml +index 90e5518d..eab23c8a 100644 +--- a/docker-compose.yml ++++ b/docker-compose.yml +@@ -419,7 +419,7 @@ services: + - php-fpm-mailcow + - sogo-mailcow + - rspamd-mailcow +- image: ghcr.io/mailcow/nginx:1.06 ++ image: ghcr.io/mailcow/nginx:1.30.1-1 + dns: + - ${IPV4_NETWORK:-172.22.1}.254 + environment: diff --git a/tasks/mailcow__mailcow-dockerized-7240/solution/solve.sh b/tasks/mailcow__mailcow-dockerized-7240/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7240/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo 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-7240/task.toml b/tasks/mailcow__mailcow-dockerized-7240/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f6df6dfef5023b0f46a72cd8dbcea5f334908b26 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7240/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/mailcow__mailcow-dockerized-7240" +description = "[Nginx] Update to 1.30.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 = "07373907e3722fe15d31e68d93a281f92d344400" +reference = "https://github.com/mailcow/mailcow-dockerized/pull/7240" +source_access = "auto" +built_at = "2026-11-16T16:09:53.196478+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:f89ce0f8e92120c1fd99b922d5443d031fa9219c7fa715927582e2c1b4b2b28b" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-05-20T15:58:29Z" +diff_format = "unified" +context_files = [ + "data/Dockerfiles/nginx/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.453521+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:8087109e03d0c73c4b2d4ef1138358fb98085796adb21469e10d3085cd03d9bf" +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-7240/tests/capture.py b/tasks/mailcow__mailcow-dockerized-7240/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7240/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture 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-7240/tests/instruction.md b/tasks/mailcow__mailcow-dockerized-7240/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6fc1550f0115fcb6bac5d765b43818b7c327074b --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7240/tests/instruction.md @@ -0,0 +1,30 @@ +# Issue + +**Title:** [Nginx] Update to 1.30.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 + +Pin nginx base image to `1.30.1-alpine`. + +### Affected Containers + +- nginx-mailcow + +## Did you run tests? + +### What did you tested? + +Built and started the container, verified `nginx -v` reports 1.30.1, +checked web UI and SOGo. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `07373907e372`. Edit files in place; the verifier captures your changes via `git diff` 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-7240/tests/oracle.patch b/tasks/mailcow__mailcow-dockerized-7240/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..5136e78645b8c7605c9d6e0ed9168d5a411fe3c4 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7240/tests/oracle.patch @@ -0,0 +1,23 @@ +diff --git a/data/Dockerfiles/nginx/Dockerfile b/data/Dockerfiles/nginx/Dockerfile +index 7d2ce34f..b8746684 100644 +--- a/data/Dockerfiles/nginx/Dockerfile ++++ b/data/Dockerfiles/nginx/Dockerfile +@@ -1,4 +1,4 @@ +-FROM nginx:alpine ++FROM nginx:1.30.1-alpine + LABEL maintainer "The Infrastructure Company GmbH " + + ENV PIP_BREAK_SYSTEM_PACKAGES=1 +diff --git a/docker-compose.yml b/docker-compose.yml +index 90e5518d..eab23c8a 100644 +--- a/docker-compose.yml ++++ b/docker-compose.yml +@@ -419,7 +419,7 @@ services: + - php-fpm-mailcow + - sogo-mailcow + - rspamd-mailcow +- image: ghcr.io/mailcow/nginx:1.06 ++ image: ghcr.io/mailcow/nginx:1.30.1-1 + dns: + - ${IPV4_NETWORK:-172.22.1}.254 + environment: diff --git a/tasks/mailcow__mailcow-dockerized-7240/tests/test.sh b/tasks/mailcow__mailcow-dockerized-7240/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..de81cd839b0f3189c211517e655a0d4fc830e2ea --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7240/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 07373907e3722fe15d31e68d93a281f92d344400 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "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-7240/tests/verifier.py b/tasks/mailcow__mailcow-dockerized-7240/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7240/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "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-7241/environment/Dockerfile b/tasks/mailcow__mailcow-dockerized-7241/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..f4eab9dcad0541e66c9590e86ec56a9d1597befb --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7241/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git 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 c9cf8d7f38448fe381d2439d673b331d95965a15 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard c9cf8d7f38448fe381d2439d673b331d95965a15 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base c9cf8d7f38448fe381d2439d673b331d95965a15 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -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-7241/instruction.md b/tasks/mailcow__mailcow-dockerized-7241/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..dd70a025527e02f52edc7989868dd2fbbb48a103 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7241/instruction.md @@ -0,0 +1,25 @@ +# Issue + +**Title:** escape HTML in quarantine table + +## 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 + +small UI fix that align user-controlled values with the auto-escaping pattern already used elsewhere: + +- `js/site/quarantine.js`: route `id`, `qid`, `sender`, `rcpt` through the DataTables text renderer + +### Affected Containers + +- php-fpm-mailcow + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `c9cf8d7f3844`. Edit files in place; the verifier captures your changes via `git diff` 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-7241/solution/patch.diff b/tasks/mailcow__mailcow-dockerized-7241/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..0f38919b3c876809334efb8d5f98e1cb429ceee0 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7241/solution/patch.diff @@ -0,0 +1,39 @@ +diff --git a/data/web/js/site/quarantine.js b/data/web/js/site/quarantine.js +index 8334ff50..a9b7845b 100644 +--- a/data/web/js/site/quarantine.js ++++ b/data/web/js/site/quarantine.js +@@ -102,18 +102,21 @@ jQuery(function($){ + { + title: 'ID', + data: 'id', +- defaultContent: '' ++ defaultContent: '', ++ render: $.fn.dataTable.render.text() + }, + { + title: lang.qid, + data: 'qid', +- defaultContent: '' ++ defaultContent: '', ++ render: $.fn.dataTable.render.text() + }, + { + title: lang.sender, + data: 'sender', + className: 'senders-mw220', +- defaultContent: '' ++ defaultContent: '', ++ render: $.fn.dataTable.render.text() + }, + { + title: lang.subj, +@@ -128,7 +131,8 @@ jQuery(function($){ + { + title: lang.rcpt, + data: 'rcpt', +- defaultContent: '' ++ defaultContent: '', ++ render: $.fn.dataTable.render.text() + }, + { + title: lang.danger, diff --git a/tasks/mailcow__mailcow-dockerized-7241/solution/solve.sh b/tasks/mailcow__mailcow-dockerized-7241/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7241/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo 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-7241/task.toml b/tasks/mailcow__mailcow-dockerized-7241/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9cb5419e789359ec5e7f38a4256e435f8d081543 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7241/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/mailcow__mailcow-dockerized-7241" +description = "escape HTML in quarantine table" + +[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 = "c9cf8d7f38448fe381d2439d673b331d95965a15" +reference = "https://github.com/mailcow/mailcow-dockerized/pull/7241" +source_access = "auto" +built_at = "2026-11-16T16:09:53.197810+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:b0a4cff3e2fa05584a620872053136df8934134b5a58b164fb421158f1c5c337" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-05-20T16:02:19Z" +diff_format = "unified" +context_files = [ + "data/web/js/site/quarantine.js", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 12 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.454032+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:af64edf62e85a7678e59619e87b20b00ca0f737d672f3478eef9d85496abe7cb" +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-7241/tests/capture.py b/tasks/mailcow__mailcow-dockerized-7241/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7241/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture 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-7241/tests/instruction.md b/tasks/mailcow__mailcow-dockerized-7241/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..dd70a025527e02f52edc7989868dd2fbbb48a103 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7241/tests/instruction.md @@ -0,0 +1,25 @@ +# Issue + +**Title:** escape HTML in quarantine table + +## 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 + +small UI fix that align user-controlled values with the auto-escaping pattern already used elsewhere: + +- `js/site/quarantine.js`: route `id`, `qid`, `sender`, `rcpt` through the DataTables text renderer + +### Affected Containers + +- php-fpm-mailcow + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `c9cf8d7f3844`. Edit files in place; the verifier captures your changes via `git diff` 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-7241/tests/oracle.patch b/tasks/mailcow__mailcow-dockerized-7241/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..0f38919b3c876809334efb8d5f98e1cb429ceee0 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7241/tests/oracle.patch @@ -0,0 +1,39 @@ +diff --git a/data/web/js/site/quarantine.js b/data/web/js/site/quarantine.js +index 8334ff50..a9b7845b 100644 +--- a/data/web/js/site/quarantine.js ++++ b/data/web/js/site/quarantine.js +@@ -102,18 +102,21 @@ jQuery(function($){ + { + title: 'ID', + data: 'id', +- defaultContent: '' ++ defaultContent: '', ++ render: $.fn.dataTable.render.text() + }, + { + title: lang.qid, + data: 'qid', +- defaultContent: '' ++ defaultContent: '', ++ render: $.fn.dataTable.render.text() + }, + { + title: lang.sender, + data: 'sender', + className: 'senders-mw220', +- defaultContent: '' ++ defaultContent: '', ++ render: $.fn.dataTable.render.text() + }, + { + title: lang.subj, +@@ -128,7 +131,8 @@ jQuery(function($){ + { + title: lang.rcpt, + data: 'rcpt', +- defaultContent: '' ++ defaultContent: '', ++ render: $.fn.dataTable.render.text() + }, + { + title: lang.danger, diff --git a/tasks/mailcow__mailcow-dockerized-7241/tests/test.sh b/tasks/mailcow__mailcow-dockerized-7241/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..a241a83011f2f1b14e81d863e96140a6dbe74fbc --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7241/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace c9cf8d7f38448fe381d2439d673b331d95965a15 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "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-7241/tests/verifier.py b/tasks/mailcow__mailcow-dockerized-7241/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7241/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "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-7252/environment/Dockerfile b/tasks/mailcow__mailcow-dockerized-7252/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..de9a493c2c6caccd317d0ffc4fed881cc4cfb63c --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7252/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git 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 aed440bcb3b33308b48f81ded97443f5b1d6ea1f 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard aed440bcb3b33308b48f81ded97443f5b1d6ea1f \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base aed440bcb3b33308b48f81ded97443f5b1d6ea1f \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -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-7252/instruction.md b/tasks/mailcow__mailcow-dockerized-7252/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1b10a7f0de79631cb60724b3c021be22d276f206 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7252/instruction.md @@ -0,0 +1,42 @@ +# Issue + +**Title:** fix unbound CVE-2026-33278 + +## 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 + +pull unbound version 1.25.1 from alpine:edge repo to fix CVE-2026-33278 (and others) + +### Affected Containers + +- unbound + +## Did you run tests? + +### What did you tested? + + + +check if unbound starts up healthy and shows correct version in startup log. + +### What were the final results? (Awaited, got) + +awaited unbound version 1.25.1 +got unbound version 1.25.1 + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `aed440bcb3b3`. Edit files in place; the verifier captures your changes via `git diff` 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-7252/solution/patch.diff b/tasks/mailcow__mailcow-dockerized-7252/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..ea0334107ee4d09dd1d96a81e1bbddf6010dfe3d --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7252/solution/patch.diff @@ -0,0 +1,33 @@ +diff --git a/data/Dockerfiles/unbound/Dockerfile b/data/Dockerfiles/unbound/Dockerfile +index 7c492138..b1ec99e4 100644 +--- a/data/Dockerfiles/unbound/Dockerfile ++++ b/data/Dockerfiles/unbound/Dockerfile +@@ -2,11 +2,14 @@ FROM alpine:3.23 + + LABEL maintainer = "The Infrastructure Company GmbH " + ++# install unbound from alpine:edge to get security patches ++RUN apk add --no-cache --repository=https://dl-cdn.alpinelinux.org/alpine/edge/main unbound ++ ++# install other packages from regular alpine stable repo + RUN apk add --update --no-cache \ + curl \ + bind-tools \ + coreutils \ +- unbound \ + bash \ + openssl \ + drill \ +diff --git a/docker-compose.yml b/docker-compose.yml +index eab23c8a..52fa15ec 100644 +--- a/docker-compose.yml ++++ b/docker-compose.yml +@@ -1,7 +1,7 @@ + services: + + unbound-mailcow: +- image: ghcr.io/mailcow/unbound:1.25 ++ image: ghcr.io/mailcow/unbound:1.25.1 + environment: + - TZ=${TZ} + - SKIP_UNBOUND_HEALTHCHECK=${SKIP_UNBOUND_HEALTHCHECK:-n} diff --git a/tasks/mailcow__mailcow-dockerized-7252/solution/solve.sh b/tasks/mailcow__mailcow-dockerized-7252/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7252/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo 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-7252/task.toml b/tasks/mailcow__mailcow-dockerized-7252/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..e5fbb0a58ff8881a50557a77bbe4558f705f054a --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7252/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/mailcow__mailcow-dockerized-7252" +description = "fix unbound CVE-2026-33278" + +[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 = "aed440bcb3b33308b48f81ded97443f5b1d6ea1f" +reference = "https://github.com/mailcow/mailcow-dockerized/pull/7252" +source_access = "auto" +built_at = "2026-11-16T16:09:53.190942+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:76a8cba0819e41b08f3c40eee54687cb4d9d46807887688f084a7253ad4b6449" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-05-26T08:41:52Z" +diff_format = "unified" +context_files = [ + "data/Dockerfiles/unbound/Dockerfile", + "docker-compose.yml", +] +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.454537+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:4960aa7c7d8babe688a0f0e7d9010da47e8862a0c18924f9bbbc1502638013cb" +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-7252/tests/capture.py b/tasks/mailcow__mailcow-dockerized-7252/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7252/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture 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-7252/tests/instruction.md b/tasks/mailcow__mailcow-dockerized-7252/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1b10a7f0de79631cb60724b3c021be22d276f206 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7252/tests/instruction.md @@ -0,0 +1,42 @@ +# Issue + +**Title:** fix unbound CVE-2026-33278 + +## 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 + +pull unbound version 1.25.1 from alpine:edge repo to fix CVE-2026-33278 (and others) + +### Affected Containers + +- unbound + +## Did you run tests? + +### What did you tested? + + + +check if unbound starts up healthy and shows correct version in startup log. + +### What were the final results? (Awaited, got) + +awaited unbound version 1.25.1 +got unbound version 1.25.1 + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `aed440bcb3b3`. Edit files in place; the verifier captures your changes via `git diff` 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-7252/tests/oracle.patch b/tasks/mailcow__mailcow-dockerized-7252/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..ea0334107ee4d09dd1d96a81e1bbddf6010dfe3d --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7252/tests/oracle.patch @@ -0,0 +1,33 @@ +diff --git a/data/Dockerfiles/unbound/Dockerfile b/data/Dockerfiles/unbound/Dockerfile +index 7c492138..b1ec99e4 100644 +--- a/data/Dockerfiles/unbound/Dockerfile ++++ b/data/Dockerfiles/unbound/Dockerfile +@@ -2,11 +2,14 @@ FROM alpine:3.23 + + LABEL maintainer = "The Infrastructure Company GmbH " + ++# install unbound from alpine:edge to get security patches ++RUN apk add --no-cache --repository=https://dl-cdn.alpinelinux.org/alpine/edge/main unbound ++ ++# install other packages from regular alpine stable repo + RUN apk add --update --no-cache \ + curl \ + bind-tools \ + coreutils \ +- unbound \ + bash \ + openssl \ + drill \ +diff --git a/docker-compose.yml b/docker-compose.yml +index eab23c8a..52fa15ec 100644 +--- a/docker-compose.yml ++++ b/docker-compose.yml +@@ -1,7 +1,7 @@ + services: + + unbound-mailcow: +- image: ghcr.io/mailcow/unbound:1.25 ++ image: ghcr.io/mailcow/unbound:1.25.1 + environment: + - TZ=${TZ} + - SKIP_UNBOUND_HEALTHCHECK=${SKIP_UNBOUND_HEALTHCHECK:-n} diff --git a/tasks/mailcow__mailcow-dockerized-7252/tests/test.sh b/tasks/mailcow__mailcow-dockerized-7252/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..567679107b20b55c89af15b08cf261a894d89a0c --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7252/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace aed440bcb3b33308b48f81ded97443f5b1d6ea1f > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "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-7252/tests/verifier.py b/tasks/mailcow__mailcow-dockerized-7252/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7252/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "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-7259/environment/Dockerfile b/tasks/mailcow__mailcow-dockerized-7259/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6cc7bb7c128bcf588b8763e6c63ca01b191019bc --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7259/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git 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 e6fa0c5099aa0c39f91c04807695b09afb4aa6a0 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard e6fa0c5099aa0c39f91c04807695b09afb4aa6a0 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base e6fa0c5099aa0c39f91c04807695b09afb4aa6a0 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -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-7259/instruction.md b/tasks/mailcow__mailcow-dockerized-7259/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e599d1ff9ceb2e46c374550744e610f8a3d84ac9 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7259/instruction.md @@ -0,0 +1,30 @@ +# Issue + +**Title:** [Nginx] Update to 1.30.2 + +## 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 + +Pin nginx base image to `1.30.2-alpine`. + +### Affected Containers + +- nginx-mailcow + +## Did you run tests? + +### What did you tested? + +Built and started the container, verified `nginx -v` reports 1.30.2, +checked web UI and SOGo. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `e6fa0c5099aa`. Edit files in place; the verifier captures your changes via `git diff` 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-7259/solution/patch.diff b/tasks/mailcow__mailcow-dockerized-7259/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..01ea72da1aec82193f16b507b69fa517642eea21 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7259/solution/patch.diff @@ -0,0 +1,23 @@ +diff --git a/data/Dockerfiles/nginx/Dockerfile b/data/Dockerfiles/nginx/Dockerfile +index b8746684..30297362 100644 +--- a/data/Dockerfiles/nginx/Dockerfile ++++ b/data/Dockerfiles/nginx/Dockerfile +@@ -1,4 +1,4 @@ +-FROM nginx:1.30.1-alpine ++FROM nginx:1.30.2-alpine + LABEL maintainer "The Infrastructure Company GmbH " + + ENV PIP_BREAK_SYSTEM_PACKAGES=1 +diff --git a/docker-compose.yml b/docker-compose.yml +index eab23c8a..af15a246 100644 +--- a/docker-compose.yml ++++ b/docker-compose.yml +@@ -419,7 +419,7 @@ services: + - php-fpm-mailcow + - sogo-mailcow + - rspamd-mailcow +- image: ghcr.io/mailcow/nginx:1.30.1-1 ++ image: ghcr.io/mailcow/nginx:1.30.2-1 + dns: + - ${IPV4_NETWORK:-172.22.1}.254 + environment: diff --git a/tasks/mailcow__mailcow-dockerized-7259/solution/solve.sh b/tasks/mailcow__mailcow-dockerized-7259/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7259/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo 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-7259/task.toml b/tasks/mailcow__mailcow-dockerized-7259/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..5d7fb699e70b5c47b3bbb2faa7568d45cb635069 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7259/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/mailcow__mailcow-dockerized-7259" +description = "[Nginx] Update to 1.30.2" + +[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 = "e6fa0c5099aa0c39f91c04807695b09afb4aa6a0" +reference = "https://github.com/mailcow/mailcow-dockerized/pull/7259" +source_access = "auto" +built_at = "2026-11-16T16:09:53.185003+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:935b4ac5d51ac9d1d47e901d2fbf85edc905e1b813b4d2cb2a834ad91b2f0d2d" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-05-26T08:37:57Z" +diff_format = "unified" +context_files = [ + "data/Dockerfiles/nginx/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.455039+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:249570f46ffeb81556b8379f39a332cb0706edaed99f5751d86c01d4de726f86" +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-7259/tests/capture.py b/tasks/mailcow__mailcow-dockerized-7259/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7259/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture 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-7259/tests/instruction.md b/tasks/mailcow__mailcow-dockerized-7259/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e599d1ff9ceb2e46c374550744e610f8a3d84ac9 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7259/tests/instruction.md @@ -0,0 +1,30 @@ +# Issue + +**Title:** [Nginx] Update to 1.30.2 + +## 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 + +Pin nginx base image to `1.30.2-alpine`. + +### Affected Containers + +- nginx-mailcow + +## Did you run tests? + +### What did you tested? + +Built and started the container, verified `nginx -v` reports 1.30.2, +checked web UI and SOGo. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `e6fa0c5099aa`. Edit files in place; the verifier captures your changes via `git diff` 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-7259/tests/oracle.patch b/tasks/mailcow__mailcow-dockerized-7259/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..01ea72da1aec82193f16b507b69fa517642eea21 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7259/tests/oracle.patch @@ -0,0 +1,23 @@ +diff --git a/data/Dockerfiles/nginx/Dockerfile b/data/Dockerfiles/nginx/Dockerfile +index b8746684..30297362 100644 +--- a/data/Dockerfiles/nginx/Dockerfile ++++ b/data/Dockerfiles/nginx/Dockerfile +@@ -1,4 +1,4 @@ +-FROM nginx:1.30.1-alpine ++FROM nginx:1.30.2-alpine + LABEL maintainer "The Infrastructure Company GmbH " + + ENV PIP_BREAK_SYSTEM_PACKAGES=1 +diff --git a/docker-compose.yml b/docker-compose.yml +index eab23c8a..af15a246 100644 +--- a/docker-compose.yml ++++ b/docker-compose.yml +@@ -419,7 +419,7 @@ services: + - php-fpm-mailcow + - sogo-mailcow + - rspamd-mailcow +- image: ghcr.io/mailcow/nginx:1.30.1-1 ++ image: ghcr.io/mailcow/nginx:1.30.2-1 + dns: + - ${IPV4_NETWORK:-172.22.1}.254 + environment: diff --git a/tasks/mailcow__mailcow-dockerized-7259/tests/test.sh b/tasks/mailcow__mailcow-dockerized-7259/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..c22b8894bc55a2dae4015fe5ba83c4c1f7d12024 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7259/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace e6fa0c5099aa0c39f91c04807695b09afb4aa6a0 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "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-7259/tests/verifier.py b/tasks/mailcow__mailcow-dockerized-7259/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7259/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "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-7262/environment/Dockerfile b/tasks/mailcow__mailcow-dockerized-7262/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..4844465a0f4740ab9bd995da23d269580ba8458e --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7262/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git 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 a7f2b2145f49ac09531a87a18489fd66ebaef06b 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard a7f2b2145f49ac09531a87a18489fd66ebaef06b \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base a7f2b2145f49ac09531a87a18489fd66ebaef06b \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -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-7262/instruction.md b/tasks/mailcow__mailcow-dockerized-7262/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..994b3bd1da9bce52ce888309765e35facf37c69d --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7262/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 `a7f2b2145f49`. Edit files in place; the verifier captures your changes via `git diff` 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-7262/solution/patch.diff b/tasks/mailcow__mailcow-dockerized-7262/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..70b85b0ee78df37cd7e56bebcc454f112f15f072 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7262/solution/patch.diff @@ -0,0 +1,163 @@ +diff --git a/data/web/lang/lang.lv-lv.json b/data/web/lang/lang.lv-lv.json +index fd29e594..df169728 100644 +--- a/data/web/lang/lang.lv-lv.json ++++ b/data/web/lang/lang.lv-lv.json +@@ -13,7 +13,7 @@ + "domain_relayhost": "Mainīt domēna relayhost", + "eas_reset": "EAS ierīču atiestatīšana", + "extend_sender_acl": "Ļauj paplašināt sūtītāja ACL ar ārējām adresēm", +- "login_as": "Pieteikšanās kā pastkastes lietotājam", ++ "login_as": "Pieteikties kā pastkastes lietotājam", + "mailbox_relayhost": "Pasta kastītes relayhost maiņa", + "prohibited": "Aizliegts ar ACL", + "protocol_access": "Protokola piekļuves maiņa", +@@ -91,12 +91,12 @@ + "activate_api": "Aktivizēt API", + "active": "Aktīvs", + "add": "Pievienot", +- "add_domain_admin": "Pievienot domēna administratoru", ++ "add_domain_admin": "Pievienot domēna pārvaldītāju", + "add_forwarding_host": "Pievienot pāradresācijas hostu", + "add_relayhost": "Pievienot Relayhost", + "add_row": "Pievienot rindu", +- "admin": "Administrators", +- "admin_details": "Labot administratora detaļas", ++ "admin": "Pārvaldītājs", ++ "admin_details": "Labot informāciju par pārvaldītāju", + "admin_domains": "Domēna uzdevumi", + "api_allow_from": "Atļaut API piekļuvi no šīm IP", + "api_key": "API atslēga", +@@ -114,7 +114,7 @@ + "dkim_keys": "ARC/DKIM atslēgas", + "dkim_private_key": "Privāta atslēga", + "domain": "Domēns", +- "domain_admins": "Domēna administratori", ++ "domain_admins": "Domēna pārvaldītāji", + "edit": "Labot", + "empty": "Nav iznākuma", + "f2b_ban_time": "Aizlieguma laiks (s)", +@@ -188,7 +188,14 @@ + "quarantine_max_score": "Atmest paziņojumu, ja e-pasta ziņojuma mēstuļu novērtējums ir augstāks par šo vērtību:
Noklusējums ir 9999.0", + "options": "Iespējas", + "password_reset_settings": "Paroļu atkopes iestatījumi", +- "password_settings": "Paroļu iestatījumi" ++ "password_settings": "Paroļu iestatījumi", ++ "add_admin": "Pievienot pārvaldītāju", ++ "admins": "Pārvaldītāji", ++ "admins_ldap": "LDAP pārvaldītāji", ++ "admin_quicklink": "Paslēpt ātro saiti uz pārvaldītāju pieteikšanās lapu", ++ "domain_admin": "Domēna pārvaldītājs", ++ "domainadmin_quicklink": "Paslēpt ātro saiti uz domēna pārvaldītāju pieteikšanās lapu", ++ "user_quicklink": "Paslēpt ātro saiti uz lietotāju pieteikšanās lapu" + }, + "danger": { + "access_denied": "Piekļuve liegta, vai nepareizi dati", +@@ -244,7 +251,10 @@ + "app_passwd_id_invalid": "Lietotnes paroles Id %s ir nederīgs", + "img_dimensions_exceeded": "Attēls pārsniedz lielāko pieļaujamo attēla lielumu", + "img_size_exceeded": "Attēls pārsniedz lielāko pieļaujamo datnes lielumu", +- "version_invalid": "Versija %s ir nederīga" ++ "version_invalid": "Versija %s ir nederīga", ++ "generic_server_error": "Atgadījās neparedzēta servera kļūda. Lūgums sazināties ar pārvaldītāju.", ++ "password_reset_na": "Paroļu atkope šobrīd nav pieejama. Lūgums sazināties ar pārvaldītāju.", ++ "recovery_email_failed": "Nevarēja nosūtīt atkopes e-pasta ziņojumu. Lūgums sazināties ar pārvaldītāju." + }, + "diagnostics": { + "cname_from_a": "Vērtība, kas iegūta no A/AAAA ieraksta. Tas tiek atbalstīts tik ilgi, kamēr ieraksts norāda uz pareizo resursu.", +@@ -266,7 +276,7 @@ + "delete2duplicates": "Izdzēst atkārtojošos vienumus galamērķī", + "description": "Apraksts", + "domain": "Labot domēnu", +- "domain_admin": "Labot domēna administratoru", ++ "domain_admin": "Labot domēna pārvaldītāju", + "domain_quota": "Domēna kvota", + "domains": "Domēni", + "dont_check_sender_acl": "Atspējot sūtītāju pārbaudi domēnam %s (+ aizstājdomēni)", +@@ -329,7 +339,8 @@ + "app_passwd": "Lietotnes parole", + "mta_sts_version": "Versija", + "mta_sts_version_info": "Norāda MTA-STS standarta versiju – pašreiz ir derīga tikai STSv1.", +- "sender_acl_disabled": "Sūtītāja pārbaude ir atspējota" ++ "sender_acl_disabled": "Sūtītāja pārbaude ir atspējota", ++ "admin": "Labot pārvaldītāju" + }, + "footer": { + "cancel": "Atcelt", +@@ -362,7 +373,14 @@ + "username": "Lietotājvārds", + "fido2_webauthn": "FIDO/WebAuthn pieteikšanās", + "mobileconfig_info": "Lūgums pieteikties kā pastkastes lietotājam, lai lejupielādētu pieprasīto Apple savienojuma profilu.", +- "other_logins": "vai pieslēgties ar" ++ "other_logins": "vai pieteikties ar", ++ "forgot_password": "> Aizmirsta parole?", ++ "login_linkstext": "Nepareiza pieteikšanās?", ++ "login_domainadmintext": "Pieteikties kā domēna pārvaldītājam", ++ "login_admintext": "Pieteikties kā pārvaldītājam", ++ "login_user": "Lietotu pieteikšanās", ++ "login_dadmin": "Domēna pārvaldītāju pieteikšanās", ++ "login_admin": "Pārvaldītāju pieteikšanās" + }, + "mailbox": { + "action": "Rīcība", +@@ -397,7 +415,7 @@ + "description": "Apraksts", + "dkim_key_length": "DKIM atslēgas garums (bits)", + "domain": "Domēns", +- "domain_admins": "Domēna administratori", ++ "domain_admins": "Domēna pārvaldītāji", + "domain_aliases": "Domēna aizstājvārdi", + "domain_quota": "Kvota", + "domain_quota_total": "Kopējais domēna ierobežojums", +@@ -507,7 +525,7 @@ + "imap_smtp_server_auth_info": "Lūgums izmantot pilnu e-pasta adresi un PLAIN autentificēšanās mehānismu.
\nPieteikšanās dati tiks šifrēti ar servera puses obligātu šifrēšanu." + }, + "success": { +- "admin_modified": "Izmaiņas administrātoram ir saglabātas", ++ "admin_modified": "Pārvaldītāja izmaiņas tika saglabātas", + "alias_added": "Aizstājadrese %s (%d) tika pievienota", + "alias_domain_removed": "Aizstājdomēns %s tika noņemts", + "alias_modified": "Aizstājadreses izmaiņas %s tika saglabātas", +@@ -518,9 +536,9 @@ + "dkim_added": "DKIM atslēga saglabāta", + "dkim_removed": "DKIM atslēga %s ir noņemta", + "domain_added": "Pievienots domēns %s", +- "domain_admin_added": "Domēna administrātors %s pievienots", +- "domain_admin_modified": "Izmaiņas domēna administrātoram %s ir saglabātas", +- "domain_admin_removed": "Domēna administrators %s tika noņemts", ++ "domain_admin_added": "Tika pievienots domēna pārvaldītājs %s", ++ "domain_admin_modified": "Domēna pārvaldītāja %s izmaiņas tika saglabātas", ++ "domain_admin_removed": "Tika noņemts domēna pārvaldītājs %s", + "domain_modified": "Izmaiņas domēnam %s ir saglabātas", + "domain_removed": "Domēns %s ir noņemts", + "eas_reset": "ActiveSync ierīces priekš lietotāja %s tika atiestatītas", +@@ -548,7 +566,9 @@ + "verified_yotp_login": "Apliecināta Yubico OTP pieteikšanās", + "app_passwd_removed": "Noņemta lietotnes parole ar Id %s", + "app_passwd_added": "Pievienota jauna lietotnes parole", +- "f2b_banlist_refreshed": "Liegumu saraksta Id tika sekmīgi atsvaidzināts." ++ "f2b_banlist_refreshed": "Liegumu saraksta Id tika sekmīgi atsvaidzināts.", ++ "admin_added": "Tika pievienots pārvaldītājs %s", ++ "admin_removed": "Tika noņemts pārvaldītājs %s" + }, + "tfa": { + "api_register": "%s izmanto Yubico Cloud API. Lūdzu iegūstiet API atslēgu priekš Jūsu atslēgashere", +@@ -569,7 +589,8 @@ + "waiting_usb_auth": "Gaida USB ierīci...

Lūdzu, tagad nospiežiet pogu uz Jūsu WebAuthn USB ierīces.", + "waiting_usb_register": "Gaida USB ierīci...

Lūgums augstāk ievadīt savu paroli un apstiprināt reģistrēšanos ar USB ierīces pogas nospiešanu.", + "yubi_otp": "Yubico OTP autentifikators", +- "authenticators": "Autentificētāji" ++ "authenticators": "Autentificētāji", ++ "u2f_deprecated_important": "Lūgums reģistrēt savu atslēgu pārvaldības lapā ar jauno WebAuthn veidu." + }, + "user": { + "action": "Rīcība", +@@ -701,7 +722,8 @@ + "warning": { + "domain_added_sogo_failed": "Domēns pievienots, bet neizdevās pārsāknēt SOGO. Lūgums pārbaudīt servera žurnālus.", + "dovecot_restart_failed": "Dovecot neizdevās pārsāknēties. Lūgums pārbaudīt žurnālus", +- "is_not_primary_alias": "Izlaists aizstājvārds %s, kas nav galvenais" ++ "is_not_primary_alias": "Izlaists aizstājvārds %s, kas nav galvenais", ++ "no_active_admin": "Nevar deaktivēt pēdējo aktīvo pārvaldītāju" + }, + "oauth2": { + "access_denied": "Lūgums pieteikties kā pastkastes īpašniekam, lai nodrošinātu piekļuvi ar OAuth2." diff --git a/tasks/mailcow__mailcow-dockerized-7262/solution/solve.sh b/tasks/mailcow__mailcow-dockerized-7262/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7262/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo 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-7262/task.toml b/tasks/mailcow__mailcow-dockerized-7262/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..92d3ae3426bb36754326849c4058f992a08f4d16 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7262/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/mailcow__mailcow-dockerized-7262" +description = "Translations update from Weblate" + +[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 = "a7f2b2145f49ac09531a87a18489fd66ebaef06b" +reference = "https://github.com/mailcow/mailcow-dockerized/pull/7262" +source_access = "auto" +built_at = "2026-11-16T16:09:53.189453+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:0ebca8bbfda12b8b91d8ef14ed27995170c248eba4412bee9ddc753fa90b00f6" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-05-26T20:02:06Z" +diff_format = "unified" +context_files = [ + "data/web/lang/lang.lv-lv.json", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 58 +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.455550+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:206a6ee81505a5547f2a21994e6952fd1fe77aa19e41d1407c0145d7fc5e2c11" +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-7262/tests/capture.py b/tasks/mailcow__mailcow-dockerized-7262/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7262/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture 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-7262/tests/instruction.md b/tasks/mailcow__mailcow-dockerized-7262/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..994b3bd1da9bce52ce888309765e35facf37c69d --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7262/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 `a7f2b2145f49`. Edit files in place; the verifier captures your changes via `git diff` 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-7262/tests/oracle.patch b/tasks/mailcow__mailcow-dockerized-7262/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..70b85b0ee78df37cd7e56bebcc454f112f15f072 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7262/tests/oracle.patch @@ -0,0 +1,163 @@ +diff --git a/data/web/lang/lang.lv-lv.json b/data/web/lang/lang.lv-lv.json +index fd29e594..df169728 100644 +--- a/data/web/lang/lang.lv-lv.json ++++ b/data/web/lang/lang.lv-lv.json +@@ -13,7 +13,7 @@ + "domain_relayhost": "Mainīt domēna relayhost", + "eas_reset": "EAS ierīču atiestatīšana", + "extend_sender_acl": "Ļauj paplašināt sūtītāja ACL ar ārējām adresēm", +- "login_as": "Pieteikšanās kā pastkastes lietotājam", ++ "login_as": "Pieteikties kā pastkastes lietotājam", + "mailbox_relayhost": "Pasta kastītes relayhost maiņa", + "prohibited": "Aizliegts ar ACL", + "protocol_access": "Protokola piekļuves maiņa", +@@ -91,12 +91,12 @@ + "activate_api": "Aktivizēt API", + "active": "Aktīvs", + "add": "Pievienot", +- "add_domain_admin": "Pievienot domēna administratoru", ++ "add_domain_admin": "Pievienot domēna pārvaldītāju", + "add_forwarding_host": "Pievienot pāradresācijas hostu", + "add_relayhost": "Pievienot Relayhost", + "add_row": "Pievienot rindu", +- "admin": "Administrators", +- "admin_details": "Labot administratora detaļas", ++ "admin": "Pārvaldītājs", ++ "admin_details": "Labot informāciju par pārvaldītāju", + "admin_domains": "Domēna uzdevumi", + "api_allow_from": "Atļaut API piekļuvi no šīm IP", + "api_key": "API atslēga", +@@ -114,7 +114,7 @@ + "dkim_keys": "ARC/DKIM atslēgas", + "dkim_private_key": "Privāta atslēga", + "domain": "Domēns", +- "domain_admins": "Domēna administratori", ++ "domain_admins": "Domēna pārvaldītāji", + "edit": "Labot", + "empty": "Nav iznākuma", + "f2b_ban_time": "Aizlieguma laiks (s)", +@@ -188,7 +188,14 @@ + "quarantine_max_score": "Atmest paziņojumu, ja e-pasta ziņojuma mēstuļu novērtējums ir augstāks par šo vērtību:
Noklusējums ir 9999.0", + "options": "Iespējas", + "password_reset_settings": "Paroļu atkopes iestatījumi", +- "password_settings": "Paroļu iestatījumi" ++ "password_settings": "Paroļu iestatījumi", ++ "add_admin": "Pievienot pārvaldītāju", ++ "admins": "Pārvaldītāji", ++ "admins_ldap": "LDAP pārvaldītāji", ++ "admin_quicklink": "Paslēpt ātro saiti uz pārvaldītāju pieteikšanās lapu", ++ "domain_admin": "Domēna pārvaldītājs", ++ "domainadmin_quicklink": "Paslēpt ātro saiti uz domēna pārvaldītāju pieteikšanās lapu", ++ "user_quicklink": "Paslēpt ātro saiti uz lietotāju pieteikšanās lapu" + }, + "danger": { + "access_denied": "Piekļuve liegta, vai nepareizi dati", +@@ -244,7 +251,10 @@ + "app_passwd_id_invalid": "Lietotnes paroles Id %s ir nederīgs", + "img_dimensions_exceeded": "Attēls pārsniedz lielāko pieļaujamo attēla lielumu", + "img_size_exceeded": "Attēls pārsniedz lielāko pieļaujamo datnes lielumu", +- "version_invalid": "Versija %s ir nederīga" ++ "version_invalid": "Versija %s ir nederīga", ++ "generic_server_error": "Atgadījās neparedzēta servera kļūda. Lūgums sazināties ar pārvaldītāju.", ++ "password_reset_na": "Paroļu atkope šobrīd nav pieejama. Lūgums sazināties ar pārvaldītāju.", ++ "recovery_email_failed": "Nevarēja nosūtīt atkopes e-pasta ziņojumu. Lūgums sazināties ar pārvaldītāju." + }, + "diagnostics": { + "cname_from_a": "Vērtība, kas iegūta no A/AAAA ieraksta. Tas tiek atbalstīts tik ilgi, kamēr ieraksts norāda uz pareizo resursu.", +@@ -266,7 +276,7 @@ + "delete2duplicates": "Izdzēst atkārtojošos vienumus galamērķī", + "description": "Apraksts", + "domain": "Labot domēnu", +- "domain_admin": "Labot domēna administratoru", ++ "domain_admin": "Labot domēna pārvaldītāju", + "domain_quota": "Domēna kvota", + "domains": "Domēni", + "dont_check_sender_acl": "Atspējot sūtītāju pārbaudi domēnam %s (+ aizstājdomēni)", +@@ -329,7 +339,8 @@ + "app_passwd": "Lietotnes parole", + "mta_sts_version": "Versija", + "mta_sts_version_info": "Norāda MTA-STS standarta versiju – pašreiz ir derīga tikai STSv1.", +- "sender_acl_disabled": "Sūtītāja pārbaude ir atspējota" ++ "sender_acl_disabled": "Sūtītāja pārbaude ir atspējota", ++ "admin": "Labot pārvaldītāju" + }, + "footer": { + "cancel": "Atcelt", +@@ -362,7 +373,14 @@ + "username": "Lietotājvārds", + "fido2_webauthn": "FIDO/WebAuthn pieteikšanās", + "mobileconfig_info": "Lūgums pieteikties kā pastkastes lietotājam, lai lejupielādētu pieprasīto Apple savienojuma profilu.", +- "other_logins": "vai pieslēgties ar" ++ "other_logins": "vai pieteikties ar", ++ "forgot_password": "> Aizmirsta parole?", ++ "login_linkstext": "Nepareiza pieteikšanās?", ++ "login_domainadmintext": "Pieteikties kā domēna pārvaldītājam", ++ "login_admintext": "Pieteikties kā pārvaldītājam", ++ "login_user": "Lietotu pieteikšanās", ++ "login_dadmin": "Domēna pārvaldītāju pieteikšanās", ++ "login_admin": "Pārvaldītāju pieteikšanās" + }, + "mailbox": { + "action": "Rīcība", +@@ -397,7 +415,7 @@ + "description": "Apraksts", + "dkim_key_length": "DKIM atslēgas garums (bits)", + "domain": "Domēns", +- "domain_admins": "Domēna administratori", ++ "domain_admins": "Domēna pārvaldītāji", + "domain_aliases": "Domēna aizstājvārdi", + "domain_quota": "Kvota", + "domain_quota_total": "Kopējais domēna ierobežojums", +@@ -507,7 +525,7 @@ + "imap_smtp_server_auth_info": "Lūgums izmantot pilnu e-pasta adresi un PLAIN autentificēšanās mehānismu.
\nPieteikšanās dati tiks šifrēti ar servera puses obligātu šifrēšanu." + }, + "success": { +- "admin_modified": "Izmaiņas administrātoram ir saglabātas", ++ "admin_modified": "Pārvaldītāja izmaiņas tika saglabātas", + "alias_added": "Aizstājadrese %s (%d) tika pievienota", + "alias_domain_removed": "Aizstājdomēns %s tika noņemts", + "alias_modified": "Aizstājadreses izmaiņas %s tika saglabātas", +@@ -518,9 +536,9 @@ + "dkim_added": "DKIM atslēga saglabāta", + "dkim_removed": "DKIM atslēga %s ir noņemta", + "domain_added": "Pievienots domēns %s", +- "domain_admin_added": "Domēna administrātors %s pievienots", +- "domain_admin_modified": "Izmaiņas domēna administrātoram %s ir saglabātas", +- "domain_admin_removed": "Domēna administrators %s tika noņemts", ++ "domain_admin_added": "Tika pievienots domēna pārvaldītājs %s", ++ "domain_admin_modified": "Domēna pārvaldītāja %s izmaiņas tika saglabātas", ++ "domain_admin_removed": "Tika noņemts domēna pārvaldītājs %s", + "domain_modified": "Izmaiņas domēnam %s ir saglabātas", + "domain_removed": "Domēns %s ir noņemts", + "eas_reset": "ActiveSync ierīces priekš lietotāja %s tika atiestatītas", +@@ -548,7 +566,9 @@ + "verified_yotp_login": "Apliecināta Yubico OTP pieteikšanās", + "app_passwd_removed": "Noņemta lietotnes parole ar Id %s", + "app_passwd_added": "Pievienota jauna lietotnes parole", +- "f2b_banlist_refreshed": "Liegumu saraksta Id tika sekmīgi atsvaidzināts." ++ "f2b_banlist_refreshed": "Liegumu saraksta Id tika sekmīgi atsvaidzināts.", ++ "admin_added": "Tika pievienots pārvaldītājs %s", ++ "admin_removed": "Tika noņemts pārvaldītājs %s" + }, + "tfa": { + "api_register": "%s izmanto Yubico Cloud API. Lūdzu iegūstiet API atslēgu priekš Jūsu atslēgashere", +@@ -569,7 +589,8 @@ + "waiting_usb_auth": "Gaida USB ierīci...

Lūdzu, tagad nospiežiet pogu uz Jūsu WebAuthn USB ierīces.", + "waiting_usb_register": "Gaida USB ierīci...

Lūgums augstāk ievadīt savu paroli un apstiprināt reģistrēšanos ar USB ierīces pogas nospiešanu.", + "yubi_otp": "Yubico OTP autentifikators", +- "authenticators": "Autentificētāji" ++ "authenticators": "Autentificētāji", ++ "u2f_deprecated_important": "Lūgums reģistrēt savu atslēgu pārvaldības lapā ar jauno WebAuthn veidu." + }, + "user": { + "action": "Rīcība", +@@ -701,7 +722,8 @@ + "warning": { + "domain_added_sogo_failed": "Domēns pievienots, bet neizdevās pārsāknēt SOGO. Lūgums pārbaudīt servera žurnālus.", + "dovecot_restart_failed": "Dovecot neizdevās pārsāknēties. Lūgums pārbaudīt žurnālus", +- "is_not_primary_alias": "Izlaists aizstājvārds %s, kas nav galvenais" ++ "is_not_primary_alias": "Izlaists aizstājvārds %s, kas nav galvenais", ++ "no_active_admin": "Nevar deaktivēt pēdējo aktīvo pārvaldītāju" + }, + "oauth2": { + "access_denied": "Lūgums pieteikties kā pastkastes īpašniekam, lai nodrošinātu piekļuvi ar OAuth2." diff --git a/tasks/mailcow__mailcow-dockerized-7262/tests/test.sh b/tasks/mailcow__mailcow-dockerized-7262/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b91723761c67601aa421a145c0f105e100da4773 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7262/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace a7f2b2145f49ac09531a87a18489fd66ebaef06b > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "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-7262/tests/verifier.py b/tasks/mailcow__mailcow-dockerized-7262/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7262/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "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-7263/environment/Dockerfile b/tasks/mailcow__mailcow-dockerized-7263/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..43a945a34f1f44c2b7e512d12cb19d2af39b0958 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7263/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git 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 eac1bf02fc9042eb3d3b5d7b198443927ceb9a57 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard eac1bf02fc9042eb3d3b5d7b198443927ceb9a57 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base eac1bf02fc9042eb3d3b5d7b198443927ceb9a57 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -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-7263/instruction.md b/tasks/mailcow__mailcow-dockerized-7263/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f39de975cddb0932d1129251d7698ac0814ad101 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7263/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 `eac1bf02fc90`. Edit files in place; the verifier captures your changes via `git diff` 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-7263/solution/patch.diff b/tasks/mailcow__mailcow-dockerized-7263/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..47d6f75372579edbe6097dbcf4a69aa1aecc58af --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7263/solution/patch.diff @@ -0,0 +1,60 @@ +diff --git a/data/web/lang/lang.vi-vn.json b/data/web/lang/lang.vi-vn.json +index 523b5dca..42813fd2 100644 +--- a/data/web/lang/lang.vi-vn.json ++++ b/data/web/lang/lang.vi-vn.json +@@ -268,10 +268,10 @@ + "includes": "Bao gồm những người nhận này", + "ip_check": "Kiểm tra IP", + "ip_check_disabled": "Kiểm tra IP đã bị vô hiệu hóa. Bạn có thể bật nó trong
Hệ thống > Cấu hình > Tùy chọn > Tùy chỉnh", +- "ip_check_opt_in": "Chọn tham gia sử dụng dịch vụ bên thứ ba ipv4.mailcow.email và ipv6.mailcow.email để phân giải địa chỉ IP bên ngoài.", ++ "ip_check_opt_in": "Đăng ký tham gia sử dụng dịch vụ bên thứ ba dùng ipv4.mailcow.email và ipv6.mailcow.email để phân giải địa chỉ IP bên ngoài.", + "is_mx_based": "Dựa trên MX", + "last_applied": "Áp dụng lần cuối", +- "license_info": "Giấy phép không bắt buộc nhưng giúp phát triển thêm.
Đăng ký GUID của bạn tại đây hoặc mua hỗ trợ cho cài đặt mailcow của bạn.", ++ "license_info": "Giấy phép tuy không bắt buộc nhưng giúp phát triển thêm.
Đăng ký GUID của bạn tại đây hoặc mua hỗ trợ cho cài đặt mailcow của bạn.", + "link": "Liên kết", + "loading": "Vui lòng đợi...", + "login_time": "Thời gian đăng nhập", +@@ -556,7 +556,9 @@ + "validity_missing": "Vui lòng gán thời hạn hiệu lực", + "value_missing": "Vui lòng cung cấp tất cả các giá trị", + "version_invalid": "Phiên bản %s không hợp lệ", +- "yotp_verification_failed": "Xác thực Yubico OTP thất bại: %s" ++ "yotp_verification_failed": "Xác thực Yubico OTP thất bại: %s", ++ "tfa_removal_blocked": "Xác thực hai yếu tố không thể bị xóa vì đây là yêu cầu bắt buộc đối với tài khoản của bạn.", ++ "quarantine_category_invalid": "Danh mục cách ly phải là một trong các loại sau : add_header, reject, all." + }, + "datatables": { + "collapse_all": "Thu gọn tất cả", +@@ -579,7 +581,9 @@ + "aria": { + "sortAscending": ": kích hoạt để sắp xếp cột tăng dần", + "sortDescending": ": kích hoạt để sắp xếp cột giảm dần" +- } ++ }, ++ "decimal": ".", ++ "thousands": "," + }, + "debug": { + "architecture": "Kiến trúc", +@@ -693,6 +697,19 @@ + "internal_info": "Bí danh nội bộ chỉ có thể truy cập từ tên miền sở hữu hoặc tên miền bí danh.", + "kind": "Loại", + "last_modified": "Sửa đổi lần cuối", +- "lookup_mx": "Đích là một biểu thức chính quy để khớp với tên MX (.*.google.com để định tuyến tất cả thư nhắm đến MX kết thúc bằng google.com qua bước nhảy này)" ++ "lookup_mx": "Đích là một biểu thức chính quy để khớp với tên MX (.*.google.com để định tuyến tất cả thư nhắm đến MX kết thúc bằng google.com qua bước nhảy này)", ++ "sender_allowed": "Cho phép gửi đi bằng bí danh", ++ "sender_allowed_info": "Nếu bị vô hiệu hóa, bí danh này chỉ có thể nhận thư. Sử dụng ACL của người gửi để ghi đè và cấp quyền gửi cho các hộp thư cụ thể.", ++ "mailbox": "Chỉnh sửa hộp thư", ++ "mailbox_quota_def": "Hạn mức hộp thư mặc định", ++ "mailbox_relayhost_info": "Chỉ áp dụng cho hộp thư và các bí danh trực tiếp, thao tác này sẽ ghi đè lên máy chủ chuyển tiếp tên miền.", ++ "mailbox_rename": "Đổi tên hộp thư", ++ "mailbox_rename_agree": "Tôi đã tạo bản sao lưu.", ++ "mailbox_rename_warning": "QUAN TRỌNG! Hãy tạo bản sao lưu trước khi đổi tên hộp thư.", ++ "mailbox_rename_alias": "Tạo tự động bí danh", ++ "mailbox_rename_title": "Tên mới của hộp thư cục bộ", ++ "max_aliases": "Số lượng Bí danh tối đa", ++ "max_mailboxes": "Số lượng hộp thư tối đa có thể có", ++ "max_quota": "Dung lượng tối đa cho mỗi hộp thư (MiB)" + } + } diff --git a/tasks/mailcow__mailcow-dockerized-7263/solution/solve.sh b/tasks/mailcow__mailcow-dockerized-7263/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7263/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo 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-7263/task.toml b/tasks/mailcow__mailcow-dockerized-7263/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..49fa598b0d0682e90af5437d0c78c3ade35d1d17 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7263/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/mailcow__mailcow-dockerized-7263" +description = "Translations update from Weblate" + +[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 = "eac1bf02fc9042eb3d3b5d7b198443927ceb9a57" +reference = "https://github.com/mailcow/mailcow-dockerized/pull/7263" +source_access = "auto" +built_at = "2026-11-16T16:09:53.188044+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:2c669afb3a8f3c3a1f51d5bbfdd9cc8eee261b32245228822514792094406cda" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-05-27T15:46:42Z" +diff_format = "unified" +context_files = [ + "data/web/lang/lang.vi-vn.json", +] +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.456047+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:8a5eb7f076f325cb328df5a670bd54317f377375387fe29486f3ea8521f2eb9a" +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-7263/tests/capture.py b/tasks/mailcow__mailcow-dockerized-7263/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7263/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture 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-7263/tests/instruction.md b/tasks/mailcow__mailcow-dockerized-7263/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f39de975cddb0932d1129251d7698ac0814ad101 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7263/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 `eac1bf02fc90`. Edit files in place; the verifier captures your changes via `git diff` 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-7263/tests/oracle.patch b/tasks/mailcow__mailcow-dockerized-7263/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..47d6f75372579edbe6097dbcf4a69aa1aecc58af --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7263/tests/oracle.patch @@ -0,0 +1,60 @@ +diff --git a/data/web/lang/lang.vi-vn.json b/data/web/lang/lang.vi-vn.json +index 523b5dca..42813fd2 100644 +--- a/data/web/lang/lang.vi-vn.json ++++ b/data/web/lang/lang.vi-vn.json +@@ -268,10 +268,10 @@ + "includes": "Bao gồm những người nhận này", + "ip_check": "Kiểm tra IP", + "ip_check_disabled": "Kiểm tra IP đã bị vô hiệu hóa. Bạn có thể bật nó trong
Hệ thống > Cấu hình > Tùy chọn > Tùy chỉnh", +- "ip_check_opt_in": "Chọn tham gia sử dụng dịch vụ bên thứ ba ipv4.mailcow.email và ipv6.mailcow.email để phân giải địa chỉ IP bên ngoài.", ++ "ip_check_opt_in": "Đăng ký tham gia sử dụng dịch vụ bên thứ ba dùng ipv4.mailcow.email và ipv6.mailcow.email để phân giải địa chỉ IP bên ngoài.", + "is_mx_based": "Dựa trên MX", + "last_applied": "Áp dụng lần cuối", +- "license_info": "Giấy phép không bắt buộc nhưng giúp phát triển thêm.
Đăng ký GUID của bạn tại đây hoặc mua hỗ trợ cho cài đặt mailcow của bạn.", ++ "license_info": "Giấy phép tuy không bắt buộc nhưng giúp phát triển thêm.
Đăng ký GUID của bạn tại đây hoặc mua hỗ trợ cho cài đặt mailcow của bạn.", + "link": "Liên kết", + "loading": "Vui lòng đợi...", + "login_time": "Thời gian đăng nhập", +@@ -556,7 +556,9 @@ + "validity_missing": "Vui lòng gán thời hạn hiệu lực", + "value_missing": "Vui lòng cung cấp tất cả các giá trị", + "version_invalid": "Phiên bản %s không hợp lệ", +- "yotp_verification_failed": "Xác thực Yubico OTP thất bại: %s" ++ "yotp_verification_failed": "Xác thực Yubico OTP thất bại: %s", ++ "tfa_removal_blocked": "Xác thực hai yếu tố không thể bị xóa vì đây là yêu cầu bắt buộc đối với tài khoản của bạn.", ++ "quarantine_category_invalid": "Danh mục cách ly phải là một trong các loại sau : add_header, reject, all." + }, + "datatables": { + "collapse_all": "Thu gọn tất cả", +@@ -579,7 +581,9 @@ + "aria": { + "sortAscending": ": kích hoạt để sắp xếp cột tăng dần", + "sortDescending": ": kích hoạt để sắp xếp cột giảm dần" +- } ++ }, ++ "decimal": ".", ++ "thousands": "," + }, + "debug": { + "architecture": "Kiến trúc", +@@ -693,6 +697,19 @@ + "internal_info": "Bí danh nội bộ chỉ có thể truy cập từ tên miền sở hữu hoặc tên miền bí danh.", + "kind": "Loại", + "last_modified": "Sửa đổi lần cuối", +- "lookup_mx": "Đích là một biểu thức chính quy để khớp với tên MX (.*.google.com để định tuyến tất cả thư nhắm đến MX kết thúc bằng google.com qua bước nhảy này)" ++ "lookup_mx": "Đích là một biểu thức chính quy để khớp với tên MX (.*.google.com để định tuyến tất cả thư nhắm đến MX kết thúc bằng google.com qua bước nhảy này)", ++ "sender_allowed": "Cho phép gửi đi bằng bí danh", ++ "sender_allowed_info": "Nếu bị vô hiệu hóa, bí danh này chỉ có thể nhận thư. Sử dụng ACL của người gửi để ghi đè và cấp quyền gửi cho các hộp thư cụ thể.", ++ "mailbox": "Chỉnh sửa hộp thư", ++ "mailbox_quota_def": "Hạn mức hộp thư mặc định", ++ "mailbox_relayhost_info": "Chỉ áp dụng cho hộp thư và các bí danh trực tiếp, thao tác này sẽ ghi đè lên máy chủ chuyển tiếp tên miền.", ++ "mailbox_rename": "Đổi tên hộp thư", ++ "mailbox_rename_agree": "Tôi đã tạo bản sao lưu.", ++ "mailbox_rename_warning": "QUAN TRỌNG! Hãy tạo bản sao lưu trước khi đổi tên hộp thư.", ++ "mailbox_rename_alias": "Tạo tự động bí danh", ++ "mailbox_rename_title": "Tên mới của hộp thư cục bộ", ++ "max_aliases": "Số lượng Bí danh tối đa", ++ "max_mailboxes": "Số lượng hộp thư tối đa có thể có", ++ "max_quota": "Dung lượng tối đa cho mỗi hộp thư (MiB)" + } + } diff --git a/tasks/mailcow__mailcow-dockerized-7263/tests/test.sh b/tasks/mailcow__mailcow-dockerized-7263/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b9686ec7f6f818847f4d826fdc0b73aaba0cbbb7 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7263/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace eac1bf02fc9042eb3d3b5d7b198443927ceb9a57 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "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-7263/tests/verifier.py b/tasks/mailcow__mailcow-dockerized-7263/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7263/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "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-7267/environment/Dockerfile b/tasks/mailcow__mailcow-dockerized-7267/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..92998880f5818bd1a35e6cc6874c23d97f1ebf45 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7267/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git 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 175878f8f1808103bc487717f2f23467c1455826 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 175878f8f1808103bc487717f2f23467c1455826 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 175878f8f1808103bc487717f2f23467c1455826 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -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-7267/instruction.md b/tasks/mailcow__mailcow-dockerized-7267/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7079bb5972a38b759a2e5cdfdb232c87cb4098df --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7267/instruction.md @@ -0,0 +1,35 @@ +# Issue + +**Title:** [SOGo] Update to 5.12.9 + +## 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? + +Update SOGo to 5.12.9 + +### Short Description + +Update SOGo to 5.12.9 and to resolve + +### Affected Containers + +- sogo-mailcow + +### What did you tested? + +- I tested that the mentioned bug in is resolved +- Ensured that sogo is updated accordingly +- + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `175878f8f180`. Edit files in place; the verifier captures your changes via `git diff` 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-7267/solution/patch.diff b/tasks/mailcow__mailcow-dockerized-7267/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..463c2a8b103bccaedd4a9d688cda9fd10431e57a --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7267/solution/patch.diff @@ -0,0 +1,36 @@ +diff --git a/data/Dockerfiles/sogo/Dockerfile b/data/Dockerfiles/sogo/Dockerfile +index 1c728720..b4b401e8 100644 +--- a/data/Dockerfiles/sogo/Dockerfile ++++ b/data/Dockerfiles/sogo/Dockerfile +@@ -1,6 +1,6 @@ + # SOGo built from source to enable security patch application + # Repository: https://github.com/Alinto/sogo +-# Version: SOGo-5.12.8 ++# Version: SOGo-5.12.9 + # + # Applied security patches: + # - +@@ -12,8 +12,8 @@ FROM debian:bookworm + LABEL maintainer="The Infrastructure Company GmbH " + + ARG DEBIAN_FRONTEND=noninteractive +-ARG SOGO_VERSION=SOGo-5.12.8 +-ARG SOPE_VERSION=SOPE-5.12.8 ++ARG SOGO_VERSION=SOGo-5.12.9 ++ARG SOPE_VERSION=SOPE-5.12.9 + # Security patches to apply (space-separated commit hashes) + ARG SOGO_SECURITY_PATCHES="" + # renovate: datasource=github-releases depName=tianon/gosu versioning=semver-coerced extractVersion=^(?.*)$ +diff --git a/docker-compose.yml b/docker-compose.yml +index 615e19f5..4da149d7 100644 +--- a/docker-compose.yml ++++ b/docker-compose.yml +@@ -200,7 +200,7 @@ services: + - phpfpm + + sogo-mailcow: +- image: ghcr.io/mailcow/sogo:5.12.8-1 ++ image: ghcr.io/mailcow/sogo:5.12.9-1 + environment: + - DBNAME=${DBNAME} + - DBUSER=${DBUSER} diff --git a/tasks/mailcow__mailcow-dockerized-7267/solution/solve.sh b/tasks/mailcow__mailcow-dockerized-7267/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7267/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo 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-7267/task.toml b/tasks/mailcow__mailcow-dockerized-7267/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..48443d60ca786167721e7e301dc8563c27e075c2 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7267/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/mailcow__mailcow-dockerized-7267" +description = "[SOGo] Update to 5.12.9" + +[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 = "175878f8f1808103bc487717f2f23467c1455826" +reference = "https://github.com/mailcow/mailcow-dockerized/pull/7267" +source_access = "auto" +built_at = "2026-11-16T16:09:53.177060+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:2b712e7ab34fb4bbca4a0b79367263c6b2637f6ba60a77c1107d90331d9170d0" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-06-11T08:04:30Z" +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.456541+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:c0ed8153b10b90a696fca85fc1939e0b57dc4c1ea214108460db900f240eefbd" +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-7267/tests/capture.py b/tasks/mailcow__mailcow-dockerized-7267/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7267/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture 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-7267/tests/instruction.md b/tasks/mailcow__mailcow-dockerized-7267/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7079bb5972a38b759a2e5cdfdb232c87cb4098df --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7267/tests/instruction.md @@ -0,0 +1,35 @@ +# Issue + +**Title:** [SOGo] Update to 5.12.9 + +## 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? + +Update SOGo to 5.12.9 + +### Short Description + +Update SOGo to 5.12.9 and to resolve + +### Affected Containers + +- sogo-mailcow + +### What did you tested? + +- I tested that the mentioned bug in is resolved +- Ensured that sogo is updated accordingly +- + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `175878f8f180`. Edit files in place; the verifier captures your changes via `git diff` 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-7267/tests/oracle.patch b/tasks/mailcow__mailcow-dockerized-7267/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..463c2a8b103bccaedd4a9d688cda9fd10431e57a --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7267/tests/oracle.patch @@ -0,0 +1,36 @@ +diff --git a/data/Dockerfiles/sogo/Dockerfile b/data/Dockerfiles/sogo/Dockerfile +index 1c728720..b4b401e8 100644 +--- a/data/Dockerfiles/sogo/Dockerfile ++++ b/data/Dockerfiles/sogo/Dockerfile +@@ -1,6 +1,6 @@ + # SOGo built from source to enable security patch application + # Repository: https://github.com/Alinto/sogo +-# Version: SOGo-5.12.8 ++# Version: SOGo-5.12.9 + # + # Applied security patches: + # - +@@ -12,8 +12,8 @@ FROM debian:bookworm + LABEL maintainer="The Infrastructure Company GmbH " + + ARG DEBIAN_FRONTEND=noninteractive +-ARG SOGO_VERSION=SOGo-5.12.8 +-ARG SOPE_VERSION=SOPE-5.12.8 ++ARG SOGO_VERSION=SOGo-5.12.9 ++ARG SOPE_VERSION=SOPE-5.12.9 + # Security patches to apply (space-separated commit hashes) + ARG SOGO_SECURITY_PATCHES="" + # renovate: datasource=github-releases depName=tianon/gosu versioning=semver-coerced extractVersion=^(?.*)$ +diff --git a/docker-compose.yml b/docker-compose.yml +index 615e19f5..4da149d7 100644 +--- a/docker-compose.yml ++++ b/docker-compose.yml +@@ -200,7 +200,7 @@ services: + - phpfpm + + sogo-mailcow: +- image: ghcr.io/mailcow/sogo:5.12.8-1 ++ image: ghcr.io/mailcow/sogo:5.12.9-1 + environment: + - DBNAME=${DBNAME} + - DBUSER=${DBUSER} diff --git a/tasks/mailcow__mailcow-dockerized-7267/tests/test.sh b/tasks/mailcow__mailcow-dockerized-7267/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..79177609eed2baa08a326b66efa15a47d5cf2936 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7267/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 175878f8f1808103bc487717f2f23467c1455826 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "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-7267/tests/verifier.py b/tasks/mailcow__mailcow-dockerized-7267/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7267/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "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-7269/environment/Dockerfile b/tasks/mailcow__mailcow-dockerized-7269/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..92998880f5818bd1a35e6cc6874c23d97f1ebf45 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7269/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git 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 175878f8f1808103bc487717f2f23467c1455826 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 175878f8f1808103bc487717f2f23467c1455826 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 175878f8f1808103bc487717f2f23467c1455826 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -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-7269/instruction.md b/tasks/mailcow__mailcow-dockerized-7269/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3e470fd2ece2750aeffb6f73fe88dd2827e2f07c --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7269/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 `175878f8f180`. Edit files in place; the verifier captures your changes via `git diff` 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-7269/solution/patch.diff b/tasks/mailcow__mailcow-dockerized-7269/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..68fc020a6b963d03054b43ed62e546656b141f8d --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7269/solution/patch.diff @@ -0,0 +1,211 @@ +diff --git a/data/conf/postfix/postscreen_access.cidr b/data/conf/postfix/postscreen_access.cidr +index 285ea7a8..70fd2651 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 Fri May 1 00:43:37 UTC 2026 ++# Whitelist generated by Postwhite v3.4 on Mon Jun 1 00:52:17 UTC 2026 + # https://github.com/stevejenkins/postwhite/ +-# 2249 total rules ++# 2186 total rules + 2a00:1450:4000::/36 permit + 2a00:1450:4864::/56 permit + 2a01:111:f400::/48 permit +@@ -56,14 +56,8 @@ + 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.40 permit +-13.107.246.40 permit + 13.108.16.0/20 permit + 13.110.208.0/21 permit + 13.110.209.0/24 permit +@@ -73,7 +67,6 @@ + 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 +@@ -177,7 +170,6 @@ + 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 +@@ -201,7 +193,6 @@ + 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 +@@ -284,7 +275,6 @@ + 51.83.17.38 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 +@@ -341,7 +331,6 @@ + 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 +@@ -408,7 +397,6 @@ + 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 +@@ -1222,9 +1210,6 @@ + 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 +@@ -1385,9 +1370,6 @@ + 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 +@@ -1470,21 +1452,7 @@ + 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 +@@ -1504,7 +1472,6 @@ + 139.138.46.219 permit + 139.138.57.55 permit + 139.138.58.119 permit +-139.167.79.86 permit + 139.177.108.0/25 permit + 139.180.17.0/24 permit + 140.238.148.191 permit +@@ -1554,12 +1521,14 @@ + 147.243.128.26 permit + 148.105.0.0/16 permit + 148.105.8.0/21 permit ++148.116.32.128/25 permit + 149.72.0.0/16 permit + 149.72.234.184 permit + 149.72.248.236 permit + 149.97.173.180 permit + 149.118.160.128/25 permit + 150.136.21.199 permit ++150.171.109.118 permit + 150.230.98.160 permit + 151.145.38.14 permit + 152.67.105.195 permit +@@ -1636,11 +1605,6 @@ + 164.152.25.241 permit + 164.177.132.168/30 permit + 165.1.100.0/25 permit +-165.173.128.0/24 permit +-165.173.180.1 permit +-165.173.180.250/31 permit +-165.173.182.250/31 permit +-165.173.189.205 permit + 166.78.68.0/22 permit + 166.78.68.221 permit + 166.78.69.169 permit +@@ -1673,19 +1637,6 @@ + 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.174.10 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 +@@ -1891,16 +1842,7 @@ + 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 +@@ -1956,8 +1898,6 @@ + 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 +@@ -2231,10 +2171,7 @@ + 2001:748:400:3301::4 permit + 2404:6800:4000::/36 permit + 2404:6800:4864::/56 permit +-2603:1061:14:72::1 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 ++2603:1061:14:40::1 permit + 2607:f8b0:4000::/36 permit + 2607:f8b0:4864::/56 permit + 2620:109:c003:104::/64 permit diff --git a/tasks/mailcow__mailcow-dockerized-7269/solution/solve.sh b/tasks/mailcow__mailcow-dockerized-7269/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7269/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo 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-7269/task.toml b/tasks/mailcow__mailcow-dockerized-7269/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..b1327d73149dbc3dc4e10c1984dc723a33c23941 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7269/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/mailcow__mailcow-dockerized-7269" +description = "[Postfix] update postscreen_access.cidr" + +[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 = "175878f8f1808103bc487717f2f23467c1455826" +reference = "https://github.com/mailcow/mailcow-dockerized/pull/7269" +source_access = "auto" +built_at = "2026-11-16T16:09:53.186600+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:24fc7af3a1912fbd8f4568f19b4acca33f6db5a89dab9d143de373b4b065f37f" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-06-09T10:20:53Z" +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 = 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.457044+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:c0ed8153b10b90a696fca85fc1939e0b57dc4c1ea214108460db900f240eefbd" +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-7269/tests/capture.py b/tasks/mailcow__mailcow-dockerized-7269/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7269/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture 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-7269/tests/instruction.md b/tasks/mailcow__mailcow-dockerized-7269/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3e470fd2ece2750aeffb6f73fe88dd2827e2f07c --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7269/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 `175878f8f180`. Edit files in place; the verifier captures your changes via `git diff` 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-7269/tests/oracle.patch b/tasks/mailcow__mailcow-dockerized-7269/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..68fc020a6b963d03054b43ed62e546656b141f8d --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7269/tests/oracle.patch @@ -0,0 +1,211 @@ +diff --git a/data/conf/postfix/postscreen_access.cidr b/data/conf/postfix/postscreen_access.cidr +index 285ea7a8..70fd2651 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 Fri May 1 00:43:37 UTC 2026 ++# Whitelist generated by Postwhite v3.4 on Mon Jun 1 00:52:17 UTC 2026 + # https://github.com/stevejenkins/postwhite/ +-# 2249 total rules ++# 2186 total rules + 2a00:1450:4000::/36 permit + 2a00:1450:4864::/56 permit + 2a01:111:f400::/48 permit +@@ -56,14 +56,8 @@ + 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.40 permit +-13.107.246.40 permit + 13.108.16.0/20 permit + 13.110.208.0/21 permit + 13.110.209.0/24 permit +@@ -73,7 +67,6 @@ + 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 +@@ -177,7 +170,6 @@ + 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 +@@ -201,7 +193,6 @@ + 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 +@@ -284,7 +275,6 @@ + 51.83.17.38 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 +@@ -341,7 +331,6 @@ + 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 +@@ -408,7 +397,6 @@ + 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 +@@ -1222,9 +1210,6 @@ + 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 +@@ -1385,9 +1370,6 @@ + 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 +@@ -1470,21 +1452,7 @@ + 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 +@@ -1504,7 +1472,6 @@ + 139.138.46.219 permit + 139.138.57.55 permit + 139.138.58.119 permit +-139.167.79.86 permit + 139.177.108.0/25 permit + 139.180.17.0/24 permit + 140.238.148.191 permit +@@ -1554,12 +1521,14 @@ + 147.243.128.26 permit + 148.105.0.0/16 permit + 148.105.8.0/21 permit ++148.116.32.128/25 permit + 149.72.0.0/16 permit + 149.72.234.184 permit + 149.72.248.236 permit + 149.97.173.180 permit + 149.118.160.128/25 permit + 150.136.21.199 permit ++150.171.109.118 permit + 150.230.98.160 permit + 151.145.38.14 permit + 152.67.105.195 permit +@@ -1636,11 +1605,6 @@ + 164.152.25.241 permit + 164.177.132.168/30 permit + 165.1.100.0/25 permit +-165.173.128.0/24 permit +-165.173.180.1 permit +-165.173.180.250/31 permit +-165.173.182.250/31 permit +-165.173.189.205 permit + 166.78.68.0/22 permit + 166.78.68.221 permit + 166.78.69.169 permit +@@ -1673,19 +1637,6 @@ + 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.174.10 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 +@@ -1891,16 +1842,7 @@ + 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 +@@ -1956,8 +1898,6 @@ + 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 +@@ -2231,10 +2171,7 @@ + 2001:748:400:3301::4 permit + 2404:6800:4000::/36 permit + 2404:6800:4864::/56 permit +-2603:1061:14:72::1 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 ++2603:1061:14:40::1 permit + 2607:f8b0:4000::/36 permit + 2607:f8b0:4864::/56 permit + 2620:109:c003:104::/64 permit diff --git a/tasks/mailcow__mailcow-dockerized-7269/tests/test.sh b/tasks/mailcow__mailcow-dockerized-7269/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..79177609eed2baa08a326b66efa15a47d5cf2936 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7269/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 175878f8f1808103bc487717f2f23467c1455826 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "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-7269/tests/verifier.py b/tasks/mailcow__mailcow-dockerized-7269/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7269/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "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-7275/environment/Dockerfile b/tasks/mailcow__mailcow-dockerized-7275/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..92998880f5818bd1a35e6cc6874c23d97f1ebf45 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7275/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git 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 175878f8f1808103bc487717f2f23467c1455826 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 175878f8f1808103bc487717f2f23467c1455826 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 175878f8f1808103bc487717f2f23467c1455826 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -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-7275/instruction.md b/tasks/mailcow__mailcow-dockerized-7275/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..94463298a1bb101e9028a1cc69952cd006806cac --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7275/instruction.md @@ -0,0 +1,37 @@ +# Issue + +**Title:** Fix force_tfa not available in mailbox template #7216 + +## 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? +Fixes force_tfa of mailbox templates being overwritten and not being available after creation + +### Short Description + +Adds a "TFA" column in the template overview table. Adds a checkbox for force_tfa in the template modification form. Fixes force_tfa being set to 0 on any modification + +### Affected Containers +- php-fpm-mailcow +- nginx-mailcow + + +## Did you run tests? +yes + +### What did you tested? +tested manually that the functionality works +verified the results with +`docker compose exec -it mysql-mailcow bash -c "mysql -u mailcow -p\$MYSQL_PASSWORD mailcow -e \"select template, JSON_PRETTY(attributes) from templates where type='mailbox';\""` + +### What were the final results? (Awaited, got) + +TFA is displayed in the mailbox template overview table. force_tfa is loaded and stored correctly. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `175878f8f180`. Edit files in place; the verifier captures your changes via `git diff` 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-7275/solution/patch.diff b/tasks/mailcow__mailcow-dockerized-7275/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..41b382eb8cca1ae1ccfc7d924540d2e6b1d96ec2 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7275/solution/patch.diff @@ -0,0 +1,168 @@ +diff --git a/data/web/api/openapi.yaml b/data/web/api/openapi.yaml +index cf54f6ad..77c58b60 100644 +--- a/data/web/api/openapi.yaml ++++ b/data/web/api/openapi.yaml +@@ -1072,6 +1072,7 @@ paths: + password2: "*" + quota: "3072" + force_pw_update: "1" ++ force_tfa: "1" + tls_enforce_in: "1" + tls_enforce_out: "1" + tags: ["tag1", "tag2"] +@@ -1118,6 +1119,7 @@ paths: + password2: atedismonsin + quota: "3072" + force_pw_update: "1" ++ force_tfa: "1" + tls_enforce_in: "1" + tls_enforce_out: "1" + tags: ["tag1", "tag2"] +@@ -1151,6 +1153,9 @@ paths: + force_pw_update: + description: forces the user to update its password on first login + type: boolean ++ force_tfa: ++ description: force 2FA enrollment at login ++ type: boolean + tls_enforce_in: + description: force inbound email tls encryption + type: boolean +@@ -2510,7 +2515,7 @@ paths: + description: >- + Using this endpoint you can perform actions on quarantine items. It is possible to release + emails from quarantine into to the inbox, or learn them as ham to improve Rspamd filtering. +- You must provide the quarantine item IDs. You can get the IDs using the GET method. ++ You must provide the quarantine item IDs. You can get the IDs using the GET method. + operationId: Edit mails in Quarantine + requestBody: + content: +@@ -3414,6 +3419,7 @@ paths: + - mailbox + - active: "1" + force_pw_update: "0" ++ force_tfa: "0" + name: Full name + password: "*" + password2: "*" +@@ -3464,6 +3470,7 @@ paths: + attr: + active: "1" + force_pw_update: "0" ++ force_tfa: "0" + name: Full name + authsource: mailcow + password: "" +@@ -3487,6 +3494,9 @@ paths: + force_pw_update: + description: force user to change password on next login + type: boolean ++ force_tfa: ++ description: force 2FA enrollment at login ++ type: boolean + name: + description: Full name of the mailbox user + type: string +@@ -4881,6 +4891,7 @@ paths: + - active: "1" + attributes: + force_pw_update: "0" ++ force_tfa: "0" + mailbox_format: "maildir:" + quarantine_notification: never + sogo_access: "1" +@@ -5805,6 +5816,7 @@ paths: + - active: "1" + attributes: + force_pw_update: "0" ++ force_tfa: "0" + mailbox_format: "maildir:" + quarantine_notification: never + sogo_access: "1" +diff --git a/data/web/inc/functions.mailbox.inc.php b/data/web/inc/functions.mailbox.inc.php +index adb330ea..b6d683e1 100644 +--- a/data/web/inc/functions.mailbox.inc.php ++++ b/data/web/inc/functions.mailbox.inc.php +@@ -3828,6 +3828,7 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { + $attr["rl_frame"] = (!empty($_data['rl_frame'])) ? $_data['rl_frame'] : $is_now['rl_frame']; + $attr["rl_value"] = (!empty($_data['rl_value'])) ? $_data['rl_value'] : $is_now['rl_value']; + $attr["force_pw_update"] = isset($_data['force_pw_update']) ? intval($_data['force_pw_update']) : $is_now['force_pw_update']; ++ $attr["force_tfa"] = isset($_data['force_tfa']) ? intval($_data['force_tfa']) : $is_now['force_tfa']; + $attr["sogo_access"] = isset($_data['sogo_access']) ? intval($_data['sogo_access']) : $is_now['sogo_access']; + $attr["active"] = isset($_data['active']) ? intval($_data['active']) : $is_now['active']; + $attr["tls_enforce_in"] = isset($_data['tls_enforce_in']) ? intval($_data['tls_enforce_in']) : $is_now['tls_enforce_in']; +diff --git a/data/web/js/site/mailbox.js b/data/web/js/site/mailbox.js +index e8edb994..0a019279 100644 +--- a/data/web/js/site/mailbox.js ++++ b/data/web/js/site/mailbox.js +@@ -424,6 +424,11 @@ $(document).ready(function() { + } else { + $('#force_pw_update').prop('checked', false); + } ++ if (template.force_tfa == 1){ ++ $('#force_tfa').prop('checked', true); ++ } else { ++ $('#force_tfa').prop('checked', false); ++ } + if (template.sogo_access == 1){ + $('#sogo_access').prop('checked', true); + } else { +@@ -1242,6 +1247,7 @@ jQuery(function($){ + item.attributes.eas_access = '' + (item.attributes.eas_access == 1 ? '1' : '0') + ''; + item.attributes.dav_access = '' + (item.attributes.dav_access == 1 ? '1' : '0') + ''; + item.attributes.sogo_access = '' + (item.attributes.sogo_access == 1 ? '1' : '0') + ''; ++ item.attributes.force_tfa = '' + (item.attributes.force_tfa == 1 ? '1' : '0') + ''; + if (item.attributes.quarantine_notification === 'never') { + item.attributes.quarantine_notification = lang.never; + } else if (item.attributes.quarantine_notification === 'hourly') { +@@ -1385,6 +1391,11 @@ jQuery(function($){ + return 1==data?'':''; + } + }, ++ { ++ title: lang.force_tfa, ++ data: 'attributes.force_tfa', ++ defaultContent: '' ++ }, + { + title: lang_edit.ratelimit, + data: 'attributes.ratelimit', +diff --git a/data/web/lang/lang.en-gb.json b/data/web/lang/lang.en-gb.json +index e786bcbe..d2412fbf 100644 +--- a/data/web/lang/lang.en-gb.json ++++ b/data/web/lang/lang.en-gb.json +@@ -929,6 +929,7 @@ + "filters": "Filters", + "fname": "Full name", + "force_pw_update": "Force password update at next login", ++ "force_tfa": "TFA", + "gal": "Global Address List", + "goto_ham": "Learn as ham", + "goto_spam": "Learn as spam", +diff --git a/data/web/templates/edit/mailbox-templates.twig b/data/web/templates/edit/mailbox-templates.twig +index ddc13958..8384fa05 100644 +--- a/data/web/templates/edit/mailbox-templates.twig ++++ b/data/web/templates/edit/mailbox-templates.twig +@@ -8,6 +8,7 @@ + + + ++ + + + +@@ -165,6 +166,14 @@ +
+
+ ++
++
++
++ ++ {{ lang.tfa.force_tfa_info }} ++
++
++
+ {% if not skip_sogo %} +
+
diff --git a/tasks/mailcow__mailcow-dockerized-7275/solution/solve.sh b/tasks/mailcow__mailcow-dockerized-7275/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7275/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo 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-7275/task.toml b/tasks/mailcow__mailcow-dockerized-7275/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..51e8aa0dff21796f99e162004e7ff71eb3cbafea --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7275/task.toml @@ -0,0 +1,72 @@ +version = "1.0" + +[task] +name = "trending/mailcow__mailcow-dockerized-7275" +description = "Fix force_tfa not available in mailbox template #7216" + +[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 = "175878f8f1808103bc487717f2f23467c1455826" +reference = "https://github.com/mailcow/mailcow-dockerized/pull/7275" +source_access = "auto" +built_at = "2026-11-16T16:09:53.180660+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:7ff62d664e29f181e12137757d278412e0616d5ff624b9c7928b7733066b4756" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-06-11T08:03:40Z" +diff_format = "unified" +context_files = [ + "data/web/api/openapi.yaml", + "data/web/inc/functions.mailbox.inc.php", + "data/web/js/site/mailbox.js", + "data/web/lang/lang.en-gb.json", + "data/web/templates/edit/mailbox-templates.twig", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 36 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.457545+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:c0ed8153b10b90a696fca85fc1939e0b57dc4c1ea214108460db900f240eefbd" +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-7275/tests/capture.py b/tasks/mailcow__mailcow-dockerized-7275/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7275/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture 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-7275/tests/instruction.md b/tasks/mailcow__mailcow-dockerized-7275/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..94463298a1bb101e9028a1cc69952cd006806cac --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7275/tests/instruction.md @@ -0,0 +1,37 @@ +# Issue + +**Title:** Fix force_tfa not available in mailbox template #7216 + +## 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? +Fixes force_tfa of mailbox templates being overwritten and not being available after creation + +### Short Description + +Adds a "TFA" column in the template overview table. Adds a checkbox for force_tfa in the template modification form. Fixes force_tfa being set to 0 on any modification + +### Affected Containers +- php-fpm-mailcow +- nginx-mailcow + + +## Did you run tests? +yes + +### What did you tested? +tested manually that the functionality works +verified the results with +`docker compose exec -it mysql-mailcow bash -c "mysql -u mailcow -p\$MYSQL_PASSWORD mailcow -e \"select template, JSON_PRETTY(attributes) from templates where type='mailbox';\""` + +### What were the final results? (Awaited, got) + +TFA is displayed in the mailbox template overview table. force_tfa is loaded and stored correctly. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `175878f8f180`. Edit files in place; the verifier captures your changes via `git diff` 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-7275/tests/oracle.patch b/tasks/mailcow__mailcow-dockerized-7275/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..41b382eb8cca1ae1ccfc7d924540d2e6b1d96ec2 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7275/tests/oracle.patch @@ -0,0 +1,168 @@ +diff --git a/data/web/api/openapi.yaml b/data/web/api/openapi.yaml +index cf54f6ad..77c58b60 100644 +--- a/data/web/api/openapi.yaml ++++ b/data/web/api/openapi.yaml +@@ -1072,6 +1072,7 @@ paths: + password2: "*" + quota: "3072" + force_pw_update: "1" ++ force_tfa: "1" + tls_enforce_in: "1" + tls_enforce_out: "1" + tags: ["tag1", "tag2"] +@@ -1118,6 +1119,7 @@ paths: + password2: atedismonsin + quota: "3072" + force_pw_update: "1" ++ force_tfa: "1" + tls_enforce_in: "1" + tls_enforce_out: "1" + tags: ["tag1", "tag2"] +@@ -1151,6 +1153,9 @@ paths: + force_pw_update: + description: forces the user to update its password on first login + type: boolean ++ force_tfa: ++ description: force 2FA enrollment at login ++ type: boolean + tls_enforce_in: + description: force inbound email tls encryption + type: boolean +@@ -2510,7 +2515,7 @@ paths: + description: >- + Using this endpoint you can perform actions on quarantine items. It is possible to release + emails from quarantine into to the inbox, or learn them as ham to improve Rspamd filtering. +- You must provide the quarantine item IDs. You can get the IDs using the GET method. ++ You must provide the quarantine item IDs. You can get the IDs using the GET method. + operationId: Edit mails in Quarantine + requestBody: + content: +@@ -3414,6 +3419,7 @@ paths: + - mailbox + - active: "1" + force_pw_update: "0" ++ force_tfa: "0" + name: Full name + password: "*" + password2: "*" +@@ -3464,6 +3470,7 @@ paths: + attr: + active: "1" + force_pw_update: "0" ++ force_tfa: "0" + name: Full name + authsource: mailcow + password: "" +@@ -3487,6 +3494,9 @@ paths: + force_pw_update: + description: force user to change password on next login + type: boolean ++ force_tfa: ++ description: force 2FA enrollment at login ++ type: boolean + name: + description: Full name of the mailbox user + type: string +@@ -4881,6 +4891,7 @@ paths: + - active: "1" + attributes: + force_pw_update: "0" ++ force_tfa: "0" + mailbox_format: "maildir:" + quarantine_notification: never + sogo_access: "1" +@@ -5805,6 +5816,7 @@ paths: + - active: "1" + attributes: + force_pw_update: "0" ++ force_tfa: "0" + mailbox_format: "maildir:" + quarantine_notification: never + sogo_access: "1" +diff --git a/data/web/inc/functions.mailbox.inc.php b/data/web/inc/functions.mailbox.inc.php +index adb330ea..b6d683e1 100644 +--- a/data/web/inc/functions.mailbox.inc.php ++++ b/data/web/inc/functions.mailbox.inc.php +@@ -3828,6 +3828,7 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { + $attr["rl_frame"] = (!empty($_data['rl_frame'])) ? $_data['rl_frame'] : $is_now['rl_frame']; + $attr["rl_value"] = (!empty($_data['rl_value'])) ? $_data['rl_value'] : $is_now['rl_value']; + $attr["force_pw_update"] = isset($_data['force_pw_update']) ? intval($_data['force_pw_update']) : $is_now['force_pw_update']; ++ $attr["force_tfa"] = isset($_data['force_tfa']) ? intval($_data['force_tfa']) : $is_now['force_tfa']; + $attr["sogo_access"] = isset($_data['sogo_access']) ? intval($_data['sogo_access']) : $is_now['sogo_access']; + $attr["active"] = isset($_data['active']) ? intval($_data['active']) : $is_now['active']; + $attr["tls_enforce_in"] = isset($_data['tls_enforce_in']) ? intval($_data['tls_enforce_in']) : $is_now['tls_enforce_in']; +diff --git a/data/web/js/site/mailbox.js b/data/web/js/site/mailbox.js +index e8edb994..0a019279 100644 +--- a/data/web/js/site/mailbox.js ++++ b/data/web/js/site/mailbox.js +@@ -424,6 +424,11 @@ $(document).ready(function() { + } else { + $('#force_pw_update').prop('checked', false); + } ++ if (template.force_tfa == 1){ ++ $('#force_tfa').prop('checked', true); ++ } else { ++ $('#force_tfa').prop('checked', false); ++ } + if (template.sogo_access == 1){ + $('#sogo_access').prop('checked', true); + } else { +@@ -1242,6 +1247,7 @@ jQuery(function($){ + item.attributes.eas_access = '' + (item.attributes.eas_access == 1 ? '1' : '0') + ''; + item.attributes.dav_access = '' + (item.attributes.dav_access == 1 ? '1' : '0') + ''; + item.attributes.sogo_access = '' + (item.attributes.sogo_access == 1 ? '1' : '0') + ''; ++ item.attributes.force_tfa = '' + (item.attributes.force_tfa == 1 ? '1' : '0') + ''; + if (item.attributes.quarantine_notification === 'never') { + item.attributes.quarantine_notification = lang.never; + } else if (item.attributes.quarantine_notification === 'hourly') { +@@ -1385,6 +1391,11 @@ jQuery(function($){ + return 1==data?'':''; + } + }, ++ { ++ title: lang.force_tfa, ++ data: 'attributes.force_tfa', ++ defaultContent: '' ++ }, + { + title: lang_edit.ratelimit, + data: 'attributes.ratelimit', +diff --git a/data/web/lang/lang.en-gb.json b/data/web/lang/lang.en-gb.json +index e786bcbe..d2412fbf 100644 +--- a/data/web/lang/lang.en-gb.json ++++ b/data/web/lang/lang.en-gb.json +@@ -929,6 +929,7 @@ + "filters": "Filters", + "fname": "Full name", + "force_pw_update": "Force password update at next login", ++ "force_tfa": "TFA", + "gal": "Global Address List", + "goto_ham": "Learn as ham", + "goto_spam": "Learn as spam", +diff --git a/data/web/templates/edit/mailbox-templates.twig b/data/web/templates/edit/mailbox-templates.twig +index ddc13958..8384fa05 100644 +--- a/data/web/templates/edit/mailbox-templates.twig ++++ b/data/web/templates/edit/mailbox-templates.twig +@@ -8,6 +8,7 @@ + + + ++ + + + +@@ -165,6 +166,14 @@ +
+
+ ++
++
++
++ ++ {{ lang.tfa.force_tfa_info }} ++
++
++
+ {% if not skip_sogo %} +
+
diff --git a/tasks/mailcow__mailcow-dockerized-7275/tests/test.sh b/tasks/mailcow__mailcow-dockerized-7275/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..79177609eed2baa08a326b66efa15a47d5cf2936 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7275/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 175878f8f1808103bc487717f2f23467c1455826 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "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-7275/tests/verifier.py b/tasks/mailcow__mailcow-dockerized-7275/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7275/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "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-7277/environment/Dockerfile b/tasks/mailcow__mailcow-dockerized-7277/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..92998880f5818bd1a35e6cc6874c23d97f1ebf45 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7277/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git 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 175878f8f1808103bc487717f2f23467c1455826 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 175878f8f1808103bc487717f2f23467c1455826 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 175878f8f1808103bc487717f2f23467c1455826 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -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-7277/instruction.md b/tasks/mailcow__mailcow-dockerized-7277/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3616dfe9e1223cf11ae41e78c200453b59f55d2f --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7277/instruction.md @@ -0,0 +1,35 @@ +# Issue + +**Title:** Refresh SOGo view after mailbox activation + +## 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 SOGo access for mailboxes that are created inactive or with login disabled and later activated. The mailbox edit path now reaches the existing SOGo static-view refresh instead of returning before it can run. + +### Affected Containers + +- php-fpm-mailcow +- sogo-mailcow + +## Did you run tests? + +### What did you tested? + +- PHP syntax check for the mailbox functions file +- diff whitespace check + +### What were the final results? (Awaited, got) + +Expected clean syntax/diff checks; got clean results. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `175878f8f180`. Edit files in place; the verifier captures your changes via `git diff` 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-7277/solution/patch.diff b/tasks/mailcow__mailcow-dockerized-7277/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..760eb57ad6233027c4b30e179874d52d78b6a5d9 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7277/solution/patch.diff @@ -0,0 +1,20 @@ +diff --git a/data/web/inc/functions.mailbox.inc.php b/data/web/inc/functions.mailbox.inc.php +index adb330ea..326f1a09 100644 +--- a/data/web/inc/functions.mailbox.inc.php ++++ b/data/web/inc/functions.mailbox.inc.php +@@ -3502,11 +3502,10 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { + 'msg' => array('mailbox_modified', $username) + ); + +- // Track affected mailboxes for SOGo update +- $update_sogo_mailboxes[] = $username; +- } +- return true; +- break; ++ // Track affected mailboxes for SOGo update ++ $update_sogo_mailboxes[] = $username; ++ } ++ break; + case 'mailbox_rename': + $domain = $_data['domain']; + $old_local_part = $_data['old_local_part']; diff --git a/tasks/mailcow__mailcow-dockerized-7277/solution/solve.sh b/tasks/mailcow__mailcow-dockerized-7277/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7277/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo 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-7277/task.toml b/tasks/mailcow__mailcow-dockerized-7277/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..2a15203c7e45ddf28bd95102fd4ab38acb02fff5 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7277/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/mailcow__mailcow-dockerized-7277" +description = "Refresh SOGo view after mailbox activation" + +[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 = "175878f8f1808103bc487717f2f23467c1455826" +reference = "https://github.com/mailcow/mailcow-dockerized/pull/7277" +source_access = "auto" +built_at = "2026-11-16T16:09:53.182124+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:c3b12b9ee273613ecec4acea1f7a260c9f1789bebe5b9fbebf08bef9344d483b" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-06-11T07:53:31Z" +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 = 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.458043+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:c0ed8153b10b90a696fca85fc1939e0b57dc4c1ea214108460db900f240eefbd" +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-7277/tests/capture.py b/tasks/mailcow__mailcow-dockerized-7277/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7277/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture 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-7277/tests/instruction.md b/tasks/mailcow__mailcow-dockerized-7277/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3616dfe9e1223cf11ae41e78c200453b59f55d2f --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7277/tests/instruction.md @@ -0,0 +1,35 @@ +# Issue + +**Title:** Refresh SOGo view after mailbox activation + +## 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 SOGo access for mailboxes that are created inactive or with login disabled and later activated. The mailbox edit path now reaches the existing SOGo static-view refresh instead of returning before it can run. + +### Affected Containers + +- php-fpm-mailcow +- sogo-mailcow + +## Did you run tests? + +### What did you tested? + +- PHP syntax check for the mailbox functions file +- diff whitespace check + +### What were the final results? (Awaited, got) + +Expected clean syntax/diff checks; got clean results. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `175878f8f180`. Edit files in place; the verifier captures your changes via `git diff` 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-7277/tests/oracle.patch b/tasks/mailcow__mailcow-dockerized-7277/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..760eb57ad6233027c4b30e179874d52d78b6a5d9 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7277/tests/oracle.patch @@ -0,0 +1,20 @@ +diff --git a/data/web/inc/functions.mailbox.inc.php b/data/web/inc/functions.mailbox.inc.php +index adb330ea..326f1a09 100644 +--- a/data/web/inc/functions.mailbox.inc.php ++++ b/data/web/inc/functions.mailbox.inc.php +@@ -3502,11 +3502,10 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { + 'msg' => array('mailbox_modified', $username) + ); + +- // Track affected mailboxes for SOGo update +- $update_sogo_mailboxes[] = $username; +- } +- return true; +- break; ++ // Track affected mailboxes for SOGo update ++ $update_sogo_mailboxes[] = $username; ++ } ++ break; + case 'mailbox_rename': + $domain = $_data['domain']; + $old_local_part = $_data['old_local_part']; diff --git a/tasks/mailcow__mailcow-dockerized-7277/tests/test.sh b/tasks/mailcow__mailcow-dockerized-7277/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..79177609eed2baa08a326b66efa15a47d5cf2936 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7277/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 175878f8f1808103bc487717f2f23467c1455826 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "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-7277/tests/verifier.py b/tasks/mailcow__mailcow-dockerized-7277/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7277/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "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-7283/environment/Dockerfile b/tasks/mailcow__mailcow-dockerized-7283/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..3af455ae8daf64a4ce52159f0736e102a6fdc64c --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7283/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git 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 5f5367f2f97df92aff2c6786dc347aa2b4edfb51 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 5f5367f2f97df92aff2c6786dc347aa2b4edfb51 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 5f5367f2f97df92aff2c6786dc347aa2b4edfb51 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -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-7283/instruction.md b/tasks/mailcow__mailcow-dockerized-7283/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..00e865bc69bdefe5c3f67614191d1c7a7b82ba06 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7283/instruction.md @@ -0,0 +1,34 @@ +# Issue + +**Title:** [Rspamd] Migrate metadata_exporter to multipart formatter + +## 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 + +** (Rspamd 4.1.0).** + +The `meta_headers` option was deprecated, so the `QUARANTINE` and `PUSHOVERMAIL` rules in `metadata_exporter` are switched to `formatter = "multipart"`. The two PHP endpoints (`pipe.php`, `pushover.php`) are adapted to read the rspamd metadata from `$_POST['metadata']` (JSON) and the raw message from `$_FILES['message']` instead of `X-Rspamd-*` HTTP headers. + +`RLINFO` is unchanged, it already uses `formatter = "json"` and does not read header values. + +### Affected Containers + +- rspamd-mailcow + +## Did you run tests? + +### What did you tested? + +- Quarantine flow: sent an EICAR test mail and verified the quarantine entry in the UI. +- PHP lint (`php -l`) on both `pipe.php` and `pushover.php`. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `5f5367f2f97d`. Edit files in place; the verifier captures your changes via `git diff` 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-7283/solution/patch.diff b/tasks/mailcow__mailcow-dockerized-7283/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..d560328b880fe41e7cf660f6a6fc15e1cebb33d4 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7283/solution/patch.diff @@ -0,0 +1,209 @@ +diff --git a/data/conf/rspamd/local.d/metadata_exporter.conf b/data/conf/rspamd/local.d/metadata_exporter.conf +index daaa79b4..cc85faac 100644 +--- a/data/conf/rspamd/local.d/metadata_exporter.conf ++++ b/data/conf/rspamd/local.d/metadata_exporter.conf +@@ -3,8 +3,7 @@ rules { + backend = "http"; + url = "http://nginx:9081/pipe.php"; + selector = "reject_no_global_bl"; +- formatter = "default"; +- meta_headers = true; ++ formatter = "multipart"; + } + RLINFO { + backend = "http"; +@@ -16,8 +15,7 @@ rules { + backend = "http"; + url = "http://nginx:9081/pushover.php"; + selector = "mailcow_rcpt"; +- formatter = "json"; +- meta_headers = true; ++ formatter = "multipart"; + } + } + +diff --git a/data/conf/rspamd/meta_exporter/pipe.php b/data/conf/rspamd/meta_exporter/pipe.php +index 003639b0..0a9ed59e 100644 +--- a/data/conf/rspamd/meta_exporter/pipe.php ++++ b/data/conf/rspamd/meta_exporter/pipe.php +@@ -32,47 +32,42 @@ function parse_email($email) { + $a = strrpos($email, '@'); + return array('local' => substr($email, 0, $a), 'domain' => substr(substr($email, $a), 1)); + } +-if (!function_exists('getallheaders')) { +- function getallheaders() { +- if (!is_array($_SERVER)) { +- return array(); +- } +- $headers = array(); +- foreach ($_SERVER as $name => $value) { +- if (substr($name, 0, 5) == 'HTTP_') { +- $headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value; +- } +- } +- return $headers; +- } ++// rspamd metadata_exporter (multipart formatter): ++// - $_POST['metadata'] JSON with the rspamd metadata ++// - $_FILES['message'] raw RFC822 message ++if (empty($_POST['metadata']) || !isset($_FILES['message']) || $_FILES['message']['error'] !== UPLOAD_ERR_OK) { ++ error_log("QUARANTINE: missing multipart parts from rspamd" . PHP_EOL); ++ http_response_code(400); ++ exit; + } + +-$raw_data_content = file_get_contents('php://input'); +-$raw_data = mb_convert_encoding($raw_data_content, 'HTML-ENTITIES', "UTF-8"); +-$headers = getallheaders(); ++$meta = json_decode($_POST['metadata'], true); ++if (!is_array($meta)) { ++ error_log("QUARANTINE: cannot decode metadata JSON" . PHP_EOL); ++ http_response_code(400); ++ exit; ++} + +-$qid = $headers['X-Rspamd-Qid']; +-$fuzzy = $headers['X-Rspamd-Fuzzy']; +-$subject = iconv_mime_decode($headers['X-Rspamd-Subject']); +-$score = $headers['X-Rspamd-Score']; +-$rcpts = $headers['X-Rspamd-Rcpt']; +-$user = $headers['X-Rspamd-User']; +-$ip = $headers['X-Rspamd-Ip']; +-$action = $headers['X-Rspamd-Action']; +-$sender = $headers['X-Rspamd-From']; +-$symbols = $headers['X-Rspamd-Symbols']; ++$raw_data_content = file_get_contents($_FILES['message']['tmp_name']); ++$raw_data = mb_convert_encoding($raw_data_content, 'HTML-ENTITIES', "UTF-8"); ++$raw_size = (int)$_FILES['message']['size']; + +-$raw_size = (int)$_SERVER['CONTENT_LENGTH']; ++$qid = $meta['qid'] ?? 'unknown'; ++$subject = iconv_mime_decode($meta['subject'] ?? ''); ++$score = $meta['score'] ?? 0; ++$rcpts = $meta['rcpt'] ?? array(); ++$user = $meta['user'] ?? 'unknown'; ++$ip = $meta['ip'] ?? 'unknown'; ++$action = $meta['action'] ?? 'no action'; ++$sender = $meta['from'] ?? ''; ++$symbols = json_encode($meta['symbols'] ?? array()); ++$fuzzy = json_encode(is_array($meta['fuzzy'] ?? null) ? $meta['fuzzy'] : array()); + + if (empty($sender)) { + error_log("QUARANTINE: Unknown sender, assuming empty-env-from@localhost" . PHP_EOL); + $sender = 'empty-env-from@localhost'; + } + +-if ($fuzzy == 'unknown') { +- $fuzzy = '[]'; +-} +- + try { + $max_size = (int)$redis->Get('Q_MAX_SIZE'); + if (($max_size * 1048576) < $raw_size) { +@@ -94,7 +89,7 @@ catch (RedisException $e) { + $rcpt_final_mailboxes = array(); + + // Loop through all rcpts +-foreach (json_decode($rcpts, true) as $rcpt) { ++foreach ($rcpts as $rcpt) { + // Remove tag + $rcpt = preg_replace('/^(.*?)\+.*(@.*)$/', '$1$2', $rcpt); + +diff --git a/data/conf/rspamd/meta_exporter/pushover.php b/data/conf/rspamd/meta_exporter/pushover.php +index efe5fdd5..a2cd0995 100644 +--- a/data/conf/rspamd/meta_exporter/pushover.php ++++ b/data/conf/rspamd/meta_exporter/pushover.php +@@ -32,50 +32,46 @@ function parse_email($email) { + $a = strrpos($email, '@'); + return array('local' => substr($email, 0, $a), 'domain' => substr(substr($email, $a), 1)); + } +-if (!function_exists('getallheaders')) { +- function getallheaders() { +- if (!is_array($_SERVER)) { +- return array(); +- } +- $headers = array(); +- foreach ($_SERVER as $name => $value) { +- if (substr($name, 0, 5) == 'HTTP_') { +- $headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value; +- } +- } +- return $headers; +- } ++// rspamd metadata_exporter (multipart formatter): metadata JSON arrives as $_POST['metadata']. ++if (empty($_POST['metadata'])) { ++ error_log("NOTIFY: missing metadata part from rspamd" . PHP_EOL); ++ http_response_code(400); ++ exit; + } + +-$headers = getallheaders(); +-$json_body = json_decode(file_get_contents('php://input')); ++$meta = json_decode($_POST['metadata'], true); ++if (!is_array($meta)) { ++ error_log("NOTIFY: cannot decode metadata JSON" . PHP_EOL); ++ http_response_code(400); ++ exit; ++} + +-$qid = $headers['X-Rspamd-Qid']; +-$rcpts = $headers['X-Rspamd-Rcpt']; +-$sender = $headers['X-Rspamd-From']; +-$ip = $headers['X-Rspamd-Ip']; +-$subject = iconv_mime_decode($headers['X-Rspamd-Subject']); +-$messageid= $json_body->message_id; ++$qid = $meta['qid'] ?? 'unknown'; ++$rcpts = $meta['rcpt'] ?? array(); ++$sender = $meta['from'] ?? ''; ++$ip = $meta['ip'] ?? 'unknown'; ++$subject = iconv_mime_decode($meta['subject'] ?? ''); ++$messageid= $meta['message_id'] ?? ''; + $priority = 0; + +-$symbols_array = json_decode($headers['X-Rspamd-Symbols'], true); ++$symbols_array = $meta['symbols'] ?? array(); + if (is_array($symbols_array)) { + foreach ($symbols_array as $symbol) { +- if ($symbol['name'] == 'HAS_X_PRIO_ONE') { ++ if (($symbol['name'] ?? null) == 'HAS_X_PRIO_ONE') { + $priority = 1; + break; + } + } + } + +-$sender_address = $json_body->header_from[0]; ++$sender_address = $meta['header_from'][0] ?? ''; + $sender_name = '-'; + if (preg_match('/(?.*?)<(?
.*?)>/i', $sender_address, $matches)) { + $sender_address = $matches['address']; + $sender_name = trim($matches['name'], '"\' '); + } + +-$to_address = $json_body->header_to[0]; ++$to_address = $meta['header_to'][0] ?? ''; + $to_name = '-'; + if (preg_match('/(?.*?)<(?
.*?)>/i', $to_address, $matches)) { + $to_address = $matches['address']; +@@ -85,7 +81,7 @@ if (preg_match('/(?.*?)<(?
.*?)>/i', $to_address, $matches)) { + $rcpt_final_mailboxes = array(); + + // Loop through all rcpts +-foreach (json_decode($rcpts, true) as $rcpt) { ++foreach ($rcpts as $rcpt) { + // Remove tag + $rcpt = preg_replace('/^(.*?)\+.*(@.*)$/', '$1$2', $rcpt); + +diff --git a/docker-compose.yml b/docker-compose.yml +index 615e19f5..16370a7b 100644 +--- a/docker-compose.yml ++++ b/docker-compose.yml +@@ -84,7 +84,7 @@ services: + - clamd + + rspamd-mailcow: +- image: ghcr.io/mailcow/rspamd:3.14.3-1 ++ image: ghcr.io/mailcow/rspamd:4.1.0-1 + stop_grace_period: 30s + depends_on: + - dovecot-mailcow diff --git a/tasks/mailcow__mailcow-dockerized-7283/solution/solve.sh b/tasks/mailcow__mailcow-dockerized-7283/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7283/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo 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-7283/task.toml b/tasks/mailcow__mailcow-dockerized-7283/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..2b55a65281608302bb0eebf6d6a4ead2573a742a --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7283/task.toml @@ -0,0 +1,71 @@ +version = "1.0" + +[task] +name = "trending/mailcow__mailcow-dockerized-7283" +description = "[Rspamd] Migrate metadata_exporter to multipart formatter" + +[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 = "5f5367f2f97df92aff2c6786dc347aa2b4edfb51" +reference = "https://github.com/mailcow/mailcow-dockerized/pull/7283" +source_access = "auto" +built_at = "2026-11-16T16:09:53.183542+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:6961a1291a66f794312745999da16c5549dbeaa5f349cb54a7b5124a73e93390" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-06-11T07:40:34Z" +diff_format = "unified" +context_files = [ + "data/conf/rspamd/local.d/metadata_exporter.conf", + "data/conf/rspamd/meta_exporter/pipe.php", + "data/conf/rspamd/meta_exporter/pushover.php", + "docker-compose.yml", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 115 +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.458563+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:8b9bc9223ca1a9654685cd3e11abd259bcf214d6fdcfff507772a278532fb826" +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-7283/tests/capture.py b/tasks/mailcow__mailcow-dockerized-7283/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7283/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture 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-7283/tests/instruction.md b/tasks/mailcow__mailcow-dockerized-7283/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..00e865bc69bdefe5c3f67614191d1c7a7b82ba06 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7283/tests/instruction.md @@ -0,0 +1,34 @@ +# Issue + +**Title:** [Rspamd] Migrate metadata_exporter to multipart formatter + +## 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 + +** (Rspamd 4.1.0).** + +The `meta_headers` option was deprecated, so the `QUARANTINE` and `PUSHOVERMAIL` rules in `metadata_exporter` are switched to `formatter = "multipart"`. The two PHP endpoints (`pipe.php`, `pushover.php`) are adapted to read the rspamd metadata from `$_POST['metadata']` (JSON) and the raw message from `$_FILES['message']` instead of `X-Rspamd-*` HTTP headers. + +`RLINFO` is unchanged, it already uses `formatter = "json"` and does not read header values. + +### Affected Containers + +- rspamd-mailcow + +## Did you run tests? + +### What did you tested? + +- Quarantine flow: sent an EICAR test mail and verified the quarantine entry in the UI. +- PHP lint (`php -l`) on both `pipe.php` and `pushover.php`. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `5f5367f2f97d`. Edit files in place; the verifier captures your changes via `git diff` 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-7283/tests/oracle.patch b/tasks/mailcow__mailcow-dockerized-7283/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..d560328b880fe41e7cf660f6a6fc15e1cebb33d4 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7283/tests/oracle.patch @@ -0,0 +1,209 @@ +diff --git a/data/conf/rspamd/local.d/metadata_exporter.conf b/data/conf/rspamd/local.d/metadata_exporter.conf +index daaa79b4..cc85faac 100644 +--- a/data/conf/rspamd/local.d/metadata_exporter.conf ++++ b/data/conf/rspamd/local.d/metadata_exporter.conf +@@ -3,8 +3,7 @@ rules { + backend = "http"; + url = "http://nginx:9081/pipe.php"; + selector = "reject_no_global_bl"; +- formatter = "default"; +- meta_headers = true; ++ formatter = "multipart"; + } + RLINFO { + backend = "http"; +@@ -16,8 +15,7 @@ rules { + backend = "http"; + url = "http://nginx:9081/pushover.php"; + selector = "mailcow_rcpt"; +- formatter = "json"; +- meta_headers = true; ++ formatter = "multipart"; + } + } + +diff --git a/data/conf/rspamd/meta_exporter/pipe.php b/data/conf/rspamd/meta_exporter/pipe.php +index 003639b0..0a9ed59e 100644 +--- a/data/conf/rspamd/meta_exporter/pipe.php ++++ b/data/conf/rspamd/meta_exporter/pipe.php +@@ -32,47 +32,42 @@ function parse_email($email) { + $a = strrpos($email, '@'); + return array('local' => substr($email, 0, $a), 'domain' => substr(substr($email, $a), 1)); + } +-if (!function_exists('getallheaders')) { +- function getallheaders() { +- if (!is_array($_SERVER)) { +- return array(); +- } +- $headers = array(); +- foreach ($_SERVER as $name => $value) { +- if (substr($name, 0, 5) == 'HTTP_') { +- $headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value; +- } +- } +- return $headers; +- } ++// rspamd metadata_exporter (multipart formatter): ++// - $_POST['metadata'] JSON with the rspamd metadata ++// - $_FILES['message'] raw RFC822 message ++if (empty($_POST['metadata']) || !isset($_FILES['message']) || $_FILES['message']['error'] !== UPLOAD_ERR_OK) { ++ error_log("QUARANTINE: missing multipart parts from rspamd" . PHP_EOL); ++ http_response_code(400); ++ exit; + } + +-$raw_data_content = file_get_contents('php://input'); +-$raw_data = mb_convert_encoding($raw_data_content, 'HTML-ENTITIES', "UTF-8"); +-$headers = getallheaders(); ++$meta = json_decode($_POST['metadata'], true); ++if (!is_array($meta)) { ++ error_log("QUARANTINE: cannot decode metadata JSON" . PHP_EOL); ++ http_response_code(400); ++ exit; ++} + +-$qid = $headers['X-Rspamd-Qid']; +-$fuzzy = $headers['X-Rspamd-Fuzzy']; +-$subject = iconv_mime_decode($headers['X-Rspamd-Subject']); +-$score = $headers['X-Rspamd-Score']; +-$rcpts = $headers['X-Rspamd-Rcpt']; +-$user = $headers['X-Rspamd-User']; +-$ip = $headers['X-Rspamd-Ip']; +-$action = $headers['X-Rspamd-Action']; +-$sender = $headers['X-Rspamd-From']; +-$symbols = $headers['X-Rspamd-Symbols']; ++$raw_data_content = file_get_contents($_FILES['message']['tmp_name']); ++$raw_data = mb_convert_encoding($raw_data_content, 'HTML-ENTITIES', "UTF-8"); ++$raw_size = (int)$_FILES['message']['size']; + +-$raw_size = (int)$_SERVER['CONTENT_LENGTH']; ++$qid = $meta['qid'] ?? 'unknown'; ++$subject = iconv_mime_decode($meta['subject'] ?? ''); ++$score = $meta['score'] ?? 0; ++$rcpts = $meta['rcpt'] ?? array(); ++$user = $meta['user'] ?? 'unknown'; ++$ip = $meta['ip'] ?? 'unknown'; ++$action = $meta['action'] ?? 'no action'; ++$sender = $meta['from'] ?? ''; ++$symbols = json_encode($meta['symbols'] ?? array()); ++$fuzzy = json_encode(is_array($meta['fuzzy'] ?? null) ? $meta['fuzzy'] : array()); + + if (empty($sender)) { + error_log("QUARANTINE: Unknown sender, assuming empty-env-from@localhost" . PHP_EOL); + $sender = 'empty-env-from@localhost'; + } + +-if ($fuzzy == 'unknown') { +- $fuzzy = '[]'; +-} +- + try { + $max_size = (int)$redis->Get('Q_MAX_SIZE'); + if (($max_size * 1048576) < $raw_size) { +@@ -94,7 +89,7 @@ catch (RedisException $e) { + $rcpt_final_mailboxes = array(); + + // Loop through all rcpts +-foreach (json_decode($rcpts, true) as $rcpt) { ++foreach ($rcpts as $rcpt) { + // Remove tag + $rcpt = preg_replace('/^(.*?)\+.*(@.*)$/', '$1$2', $rcpt); + +diff --git a/data/conf/rspamd/meta_exporter/pushover.php b/data/conf/rspamd/meta_exporter/pushover.php +index efe5fdd5..a2cd0995 100644 +--- a/data/conf/rspamd/meta_exporter/pushover.php ++++ b/data/conf/rspamd/meta_exporter/pushover.php +@@ -32,50 +32,46 @@ function parse_email($email) { + $a = strrpos($email, '@'); + return array('local' => substr($email, 0, $a), 'domain' => substr(substr($email, $a), 1)); + } +-if (!function_exists('getallheaders')) { +- function getallheaders() { +- if (!is_array($_SERVER)) { +- return array(); +- } +- $headers = array(); +- foreach ($_SERVER as $name => $value) { +- if (substr($name, 0, 5) == 'HTTP_') { +- $headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value; +- } +- } +- return $headers; +- } ++// rspamd metadata_exporter (multipart formatter): metadata JSON arrives as $_POST['metadata']. ++if (empty($_POST['metadata'])) { ++ error_log("NOTIFY: missing metadata part from rspamd" . PHP_EOL); ++ http_response_code(400); ++ exit; + } + +-$headers = getallheaders(); +-$json_body = json_decode(file_get_contents('php://input')); ++$meta = json_decode($_POST['metadata'], true); ++if (!is_array($meta)) { ++ error_log("NOTIFY: cannot decode metadata JSON" . PHP_EOL); ++ http_response_code(400); ++ exit; ++} + +-$qid = $headers['X-Rspamd-Qid']; +-$rcpts = $headers['X-Rspamd-Rcpt']; +-$sender = $headers['X-Rspamd-From']; +-$ip = $headers['X-Rspamd-Ip']; +-$subject = iconv_mime_decode($headers['X-Rspamd-Subject']); +-$messageid= $json_body->message_id; ++$qid = $meta['qid'] ?? 'unknown'; ++$rcpts = $meta['rcpt'] ?? array(); ++$sender = $meta['from'] ?? ''; ++$ip = $meta['ip'] ?? 'unknown'; ++$subject = iconv_mime_decode($meta['subject'] ?? ''); ++$messageid= $meta['message_id'] ?? ''; + $priority = 0; + +-$symbols_array = json_decode($headers['X-Rspamd-Symbols'], true); ++$symbols_array = $meta['symbols'] ?? array(); + if (is_array($symbols_array)) { + foreach ($symbols_array as $symbol) { +- if ($symbol['name'] == 'HAS_X_PRIO_ONE') { ++ if (($symbol['name'] ?? null) == 'HAS_X_PRIO_ONE') { + $priority = 1; + break; + } + } + } + +-$sender_address = $json_body->header_from[0]; ++$sender_address = $meta['header_from'][0] ?? ''; + $sender_name = '-'; + if (preg_match('/(?.*?)<(?
.*?)>/i', $sender_address, $matches)) { + $sender_address = $matches['address']; + $sender_name = trim($matches['name'], '"\' '); + } + +-$to_address = $json_body->header_to[0]; ++$to_address = $meta['header_to'][0] ?? ''; + $to_name = '-'; + if (preg_match('/(?.*?)<(?
.*?)>/i', $to_address, $matches)) { + $to_address = $matches['address']; +@@ -85,7 +81,7 @@ if (preg_match('/(?.*?)<(?
.*?)>/i', $to_address, $matches)) { + $rcpt_final_mailboxes = array(); + + // Loop through all rcpts +-foreach (json_decode($rcpts, true) as $rcpt) { ++foreach ($rcpts as $rcpt) { + // Remove tag + $rcpt = preg_replace('/^(.*?)\+.*(@.*)$/', '$1$2', $rcpt); + +diff --git a/docker-compose.yml b/docker-compose.yml +index 615e19f5..16370a7b 100644 +--- a/docker-compose.yml ++++ b/docker-compose.yml +@@ -84,7 +84,7 @@ services: + - clamd + + rspamd-mailcow: +- image: ghcr.io/mailcow/rspamd:3.14.3-1 ++ image: ghcr.io/mailcow/rspamd:4.1.0-1 + stop_grace_period: 30s + depends_on: + - dovecot-mailcow diff --git a/tasks/mailcow__mailcow-dockerized-7283/tests/test.sh b/tasks/mailcow__mailcow-dockerized-7283/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ebb0011846b16f9e19fb3dd100b44b71a1361fec --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7283/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 5f5367f2f97df92aff2c6786dc347aa2b4edfb51 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "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-7283/tests/verifier.py b/tasks/mailcow__mailcow-dockerized-7283/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7283/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "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-7290/environment/Dockerfile b/tasks/mailcow__mailcow-dockerized-7290/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b2c625193f841c380ac4767f2c08689b0e5b91b6 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7290/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git 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 7e6c36dce1c106e95334410ad8313d1174fe15fa 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 7e6c36dce1c106e95334410ad8313d1174fe15fa \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 7e6c36dce1c106e95334410ad8313d1174fe15fa \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -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-7290/instruction.md b/tasks/mailcow__mailcow-dockerized-7290/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ce05702170c8fe444192b942cf84c246377706e6 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7290/instruction.md @@ -0,0 +1,70 @@ +# Issue + +**Title:** Fix #7150: passwd-verify.lua wipes auth cache during any nginx outage + +## 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 + +. + +`passwd-verify.lua` wiped the Dovecot auth cache for affected users whenever +a host reboot, a full-stack snapshot/backup, or any transient Docker network blip. + +On a network-level failure, `https.request` returns `nil` plus an error *string* +(e.g. `"host or service not provided, or not known"`), so `c` is not a numeric HTTP +status code. The existing `if c ~= 200 and c ~= 401` check treated this identically +to a credential rejection and returned `PASSDB_RESULT_PASSWORD_MISMATCH`, which clears +the cache entry — causing hard auth failures for reconnecting clients (iOS Mail in +particular, which has no Keychain fallback). + +This PR adds a guard ahead of the HTTP-status check: when `c` is not a number, the +request failed at the network level, so it returns `PASSDB_RESULT_INTERNAL_FAILURE` +("Upstream unreachable"), which **keeps** the existing cache entry instead of wiping +it. Genuine HTTP responses (200/401, and 4xx/5xx errors) are handled exactly as before. +The log concatenation is also hardened to `tostring(c)` so it can't error on a +non-string/nil value. + +This restores the pre-2025-05 behavior where a brief nginx interruption was benign for +already-authenticated clients. + +### Affected Containers + +- dovecot-mailcow + +## Did you run tests? + +Yes — tested on a live mailcow instance by overriding `passwd-verify.lua` and exercising +the real-world scenario that originally surfaced the bug. + +### What did you tested? + +The Dovecot auth path (`dovecot-mailcow`) through a full-stack restart, using my backup +procedure as the trigger: stop the entire stack, snapshot the volumes, then start the +stack again. This is exactly the kind of operation that leaves `nginx:9082` unreachable +while Dovecot auth workers are still serving reconnecting IMAP clients. + +I first noticed the failure on the stock file, then applied the patched +`passwd-verify.lua` as an override and repeated the same backup/restart cycle with active +IMAP clients connected. + +### What were the final results? (Awaited, got) + +- Stock file, full-stack restart → **awaited:** the documented bug. **got:** confirmed — + auth cache entries for connected users were wiped and clients hit hard authentication + failures during the nginx-unavailable window. +- Patched file, same full-stack restart → **awaited:** cache entries retained, clients + unaffected. **got:** as awaited — no cache wipe, and connected IMAP clients stayed + authenticated across the entire stop/snapshot/restart cycle, with no re-auth prompts. +- `luac -p data/conf/dovecot/auth/passwd-verify.lua` → **awaited:** no syntax errors. + **got:** syntax OK. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `7e6c36dce1c1`. Edit files in place; the verifier captures your changes via `git diff` 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-7290/solution/patch.diff b/tasks/mailcow__mailcow-dockerized-7290/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..6c48521fd376bdd269d8e55e7ae5f51d9904390b --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7290/solution/patch.diff @@ -0,0 +1,23 @@ +diff --git a/data/conf/dovecot/auth/passwd-verify.lua b/data/conf/dovecot/auth/passwd-verify.lua +index ea847932..a22488ea 100644 +--- a/data/conf/dovecot/auth/passwd-verify.lua ++++ b/data/conf/dovecot/auth/passwd-verify.lua +@@ -32,8 +32,17 @@ function auth_password_verify(request, password) + -- Returning PASSDB_RESULT_PASSWORD_MISMATCH will reset the user's auth cache entry. + -- Returning PASSDB_RESULT_INTERNAL_FAILURE keeps the existing cache entry, + -- even if the TTL has expired. Useful to avoid cache eviction during backend issues. ++ ++ -- On a network-level failure (nginx unreachable, DNS failure, timeout) https.request ++ -- returns nil plus an error string, so c is not a numeric HTTP status code. Treat this ++ -- as a backend outage and keep the cache entry, rather than wiping it as a mismatch. ++ if type(c) ~= "number" then ++ dovecot.i_info("HTTP request to auth backend failed with " .. tostring(c) .. " for user " .. request.user) ++ return dovecot.auth.PASSDB_RESULT_INTERNAL_FAILURE, "Upstream unreachable" ++ end ++ + if c ~= 200 and c ~= 401 then +- dovecot.i_info("HTTP request failed with " .. c .. " for user " .. request.user) ++ dovecot.i_info("HTTP request failed with " .. tostring(c) .. " for user " .. request.user) + return dovecot.auth.PASSDB_RESULT_PASSWORD_MISMATCH, "Upstream error" + end + diff --git a/tasks/mailcow__mailcow-dockerized-7290/solution/solve.sh b/tasks/mailcow__mailcow-dockerized-7290/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7290/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo 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-7290/task.toml b/tasks/mailcow__mailcow-dockerized-7290/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..62205f90b7f53a94aa99aa4369743c884fde64bf --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7290/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/mailcow__mailcow-dockerized-7290" +description = "Fix #7150: passwd-verify.lua wipes auth cache during any nginx outage" + +[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 = "7e6c36dce1c106e95334410ad8313d1174fe15fa" +reference = "https://github.com/mailcow/mailcow-dockerized/pull/7290" +source_access = "auto" +built_at = "2026-11-16T16:09:53.151884+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:f2efc03d1c79ab0459811b088eef0a7ec621c0d46132a9652dc46005691cfcf3" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-08-18T11:27:02Z" +diff_format = "unified" +context_files = [ + "data/conf/dovecot/auth/passwd-verify.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 11 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.459075+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:b20c70b991c670bc3c7877be9436e5223b7e5c7ee60c9d63446d7be41500c972" +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-7290/tests/capture.py b/tasks/mailcow__mailcow-dockerized-7290/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7290/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture 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-7290/tests/instruction.md b/tasks/mailcow__mailcow-dockerized-7290/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ce05702170c8fe444192b942cf84c246377706e6 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7290/tests/instruction.md @@ -0,0 +1,70 @@ +# Issue + +**Title:** Fix #7150: passwd-verify.lua wipes auth cache during any nginx outage + +## 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 + +. + +`passwd-verify.lua` wiped the Dovecot auth cache for affected users whenever +a host reboot, a full-stack snapshot/backup, or any transient Docker network blip. + +On a network-level failure, `https.request` returns `nil` plus an error *string* +(e.g. `"host or service not provided, or not known"`), so `c` is not a numeric HTTP +status code. The existing `if c ~= 200 and c ~= 401` check treated this identically +to a credential rejection and returned `PASSDB_RESULT_PASSWORD_MISMATCH`, which clears +the cache entry — causing hard auth failures for reconnecting clients (iOS Mail in +particular, which has no Keychain fallback). + +This PR adds a guard ahead of the HTTP-status check: when `c` is not a number, the +request failed at the network level, so it returns `PASSDB_RESULT_INTERNAL_FAILURE` +("Upstream unreachable"), which **keeps** the existing cache entry instead of wiping +it. Genuine HTTP responses (200/401, and 4xx/5xx errors) are handled exactly as before. +The log concatenation is also hardened to `tostring(c)` so it can't error on a +non-string/nil value. + +This restores the pre-2025-05 behavior where a brief nginx interruption was benign for +already-authenticated clients. + +### Affected Containers + +- dovecot-mailcow + +## Did you run tests? + +Yes — tested on a live mailcow instance by overriding `passwd-verify.lua` and exercising +the real-world scenario that originally surfaced the bug. + +### What did you tested? + +The Dovecot auth path (`dovecot-mailcow`) through a full-stack restart, using my backup +procedure as the trigger: stop the entire stack, snapshot the volumes, then start the +stack again. This is exactly the kind of operation that leaves `nginx:9082` unreachable +while Dovecot auth workers are still serving reconnecting IMAP clients. + +I first noticed the failure on the stock file, then applied the patched +`passwd-verify.lua` as an override and repeated the same backup/restart cycle with active +IMAP clients connected. + +### What were the final results? (Awaited, got) + +- Stock file, full-stack restart → **awaited:** the documented bug. **got:** confirmed — + auth cache entries for connected users were wiped and clients hit hard authentication + failures during the nginx-unavailable window. +- Patched file, same full-stack restart → **awaited:** cache entries retained, clients + unaffected. **got:** as awaited — no cache wipe, and connected IMAP clients stayed + authenticated across the entire stop/snapshot/restart cycle, with no re-auth prompts. +- `luac -p data/conf/dovecot/auth/passwd-verify.lua` → **awaited:** no syntax errors. + **got:** syntax OK. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `7e6c36dce1c1`. Edit files in place; the verifier captures your changes via `git diff` 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-7290/tests/oracle.patch b/tasks/mailcow__mailcow-dockerized-7290/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..6c48521fd376bdd269d8e55e7ae5f51d9904390b --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7290/tests/oracle.patch @@ -0,0 +1,23 @@ +diff --git a/data/conf/dovecot/auth/passwd-verify.lua b/data/conf/dovecot/auth/passwd-verify.lua +index ea847932..a22488ea 100644 +--- a/data/conf/dovecot/auth/passwd-verify.lua ++++ b/data/conf/dovecot/auth/passwd-verify.lua +@@ -32,8 +32,17 @@ function auth_password_verify(request, password) + -- Returning PASSDB_RESULT_PASSWORD_MISMATCH will reset the user's auth cache entry. + -- Returning PASSDB_RESULT_INTERNAL_FAILURE keeps the existing cache entry, + -- even if the TTL has expired. Useful to avoid cache eviction during backend issues. ++ ++ -- On a network-level failure (nginx unreachable, DNS failure, timeout) https.request ++ -- returns nil plus an error string, so c is not a numeric HTTP status code. Treat this ++ -- as a backend outage and keep the cache entry, rather than wiping it as a mismatch. ++ if type(c) ~= "number" then ++ dovecot.i_info("HTTP request to auth backend failed with " .. tostring(c) .. " for user " .. request.user) ++ return dovecot.auth.PASSDB_RESULT_INTERNAL_FAILURE, "Upstream unreachable" ++ end ++ + if c ~= 200 and c ~= 401 then +- dovecot.i_info("HTTP request failed with " .. c .. " for user " .. request.user) ++ dovecot.i_info("HTTP request failed with " .. tostring(c) .. " for user " .. request.user) + return dovecot.auth.PASSDB_RESULT_PASSWORD_MISMATCH, "Upstream error" + end + diff --git a/tasks/mailcow__mailcow-dockerized-7290/tests/test.sh b/tasks/mailcow__mailcow-dockerized-7290/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..62e1a88972f28163918336195f3e499d68c10c09 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7290/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 7e6c36dce1c106e95334410ad8313d1174fe15fa > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "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-7290/tests/verifier.py b/tasks/mailcow__mailcow-dockerized-7290/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7290/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "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-7300/environment/Dockerfile b/tasks/mailcow__mailcow-dockerized-7300/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b2c625193f841c380ac4767f2c08689b0e5b91b6 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7300/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git 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 7e6c36dce1c106e95334410ad8313d1174fe15fa 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 7e6c36dce1c106e95334410ad8313d1174fe15fa \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 7e6c36dce1c106e95334410ad8313d1174fe15fa \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -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-7300/instruction.md b/tasks/mailcow__mailcow-dockerized-7300/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f40319e059710a6d5d0df7ffcab8fe2a666829d1 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7300/instruction.md @@ -0,0 +1,74 @@ +# Issue + +**Title:** Update actions/checkout action to v7 + +## Description + +This PR contains the following updates: + +| Package | Type | Update | Change | +|---|---|---|---| +| [actions/checkout](https://redirect.github.com/actions/checkout) | action | major | `v6` → `v7` | + +--- + +### Release Notes + +
+actions/checkout (actions/checkout) + +### [`v7.0.0`](https://redirect.github.com/actions/checkout/blob/HEAD/CHANGELOG.md#v700) + +[Compare Source](https://redirect.github.com/actions/checkout/compare/v7.0.0...v7.0.0) + +- Block checking out fork PR for pull\_request\_target and workflow\_run by [@​aiqiaoy](https://redirect.github.com/aiqiaoy) in +- Bump actions/publish-immutable-action from 0.0.3 to 0.0.4 in the minor-actions-dependencies group across 1 directory by [@​dependabot](https://redirect.github.com/dependabot)\[bot] in +- Bump flatted from 3.3.1 to 3.4.2 by [@​dependabot](https://redirect.github.com/dependabot)\[bot] in +- Bump js-yaml from 4.1.0 to 4.2.0 by [@​dependabot](https://redirect.github.com/dependabot)\[bot] in +- Bump [@​actions/core](https://redirect.github.com/actions/core) and [@​actions/tool-cache](https://redirect.github.com/actions/tool-cache) and Remove uuid by [@​dependabot](https://redirect.github.com/dependabot)\[bot] in +- upgrade module to esm and update dependencies by [@​aiqiaoy](https://redirect.github.com/aiqiaoy) in +- Bump the minor-npm-dependencies group across 1 directory with 3 updates by [@​dependabot](https://redirect.github.com/dependabot)\[bot] in + +### [`v7`](https://redirect.github.com/actions/checkout/blob/HEAD/CHANGELOG.md#v700) + +[Compare Source](https://redirect.github.com/actions/checkout/compare/v6.0.3...v7.0.0) + +- Block checking out fork PR for pull\_request\_target and workflow\_run by [@​aiqiaoy](https://redirect.github.com/aiqiaoy) in +- Bump actions/publish-immutable-action from 0.0.3 to 0.0.4 in the minor-actions-dependencies group across 1 directory by [@​dependabot](https://redirect.github.com/dependabot)\[bot] in +- Bump flatted from 3.3.1 to 3.4.2 by [@​dependabot](https://redirect.github.com/dependabot)\[bot] in +- Bump js-yaml from 4.1.0 to 4.2.0 by [@​dependabot](https://redirect.github.com/dependabot)\[bot] in +- Bump [@​actions/core](https://redirect.github.com/actions/core) and [@​actions/tool-cache](https://redirect.github.com/actions/tool-cache) and Remove uuid by [@​dependabot](https://redirect.github.com/dependabot)\[bot] in +- upgrade module to esm and update dependencies by [@​aiqiaoy](https://redirect.github.com/aiqiaoy) in +- Bump the minor-npm-dependencies group across 1 directory with 3 updates by [@​dependabot](https://redirect.github.com/dependabot)\[bot] in + +
+ +--- + +### Configuration + +📅 **Schedule**: (in timezone Europe/Berlin) + +- Branch creation + - At any time (no schedule defined) +- Automerge + - At any time (no schedule defined) + +🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied. + +♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox. + +🔕 **Ignore**: Close this PR and you won't be reminded about this update again. + +--- + + - [ ] If you want to rebase/retry this PR, check this box + +--- + +This PR was generated by [Mend Renovate](https://mend.io/renovate/). View the [repository job log](https://developer.mend.io/github/mailcow/mailcow-dockerized). + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `7e6c36dce1c1`. Edit files in place; the verifier captures your changes via `git diff` 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-7300/solution/patch.diff b/tasks/mailcow__mailcow-dockerized-7300/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..cad0067cb10f101eade1bb4f358734432f94ee2f --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7300/solution/patch.diff @@ -0,0 +1,52 @@ +diff --git a/.github/workflows/image_builds.yml b/.github/workflows/image_builds.yml +index c8ec7cca..aa56b038 100644 +--- a/.github/workflows/image_builds.yml ++++ b/.github/workflows/image_builds.yml +@@ -27,7 +27,7 @@ jobs: + - "watchdog-mailcow" + runs-on: ubuntu-latest + steps: +- - uses: actions/checkout@v6 ++ - uses: actions/checkout@v7 + - name: Setup Docker + run: | + curl -sSL https://get.docker.com/ | CHANNEL=stable sudo sh +diff --git a/.github/workflows/pr_to_nightly.yml b/.github/workflows/pr_to_nightly.yml +index 01d7a91a..5c361af7 100644 +--- a/.github/workflows/pr_to_nightly.yml ++++ b/.github/workflows/pr_to_nightly.yml +@@ -8,7 +8,7 @@ jobs: + runs-on: ubuntu-latest + steps: + - name: Checkout repository +- uses: actions/checkout@v6 ++ uses: actions/checkout@v7 + with: + fetch-depth: 0 + - name: Run the Action +diff --git a/.github/workflows/rebuild_backup_image.yml b/.github/workflows/rebuild_backup_image.yml +index b18d339b..4490afee 100644 +--- a/.github/workflows/rebuild_backup_image.yml ++++ b/.github/workflows/rebuild_backup_image.yml +@@ -13,7 +13,7 @@ jobs: + packages: write + steps: + - name: Checkout +- uses: actions/checkout@v6 ++ uses: actions/checkout@v7 + + - name: Set up QEMU + uses: docker/setup-qemu-action@v4 +diff --git a/.github/workflows/update_postscreen_access_list.yml b/.github/workflows/update_postscreen_access_list.yml +index 066616ae..ed63281c 100644 +--- a/.github/workflows/update_postscreen_access_list.yml ++++ b/.github/workflows/update_postscreen_access_list.yml +@@ -15,7 +15,7 @@ jobs: + runs-on: ubuntu-latest + steps: + - name: Checkout +- uses: actions/checkout@v6 ++ uses: actions/checkout@v7 + + - name: Generate postscreen_access.cidr + run: | diff --git a/tasks/mailcow__mailcow-dockerized-7300/solution/solve.sh b/tasks/mailcow__mailcow-dockerized-7300/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7300/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo 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-7300/task.toml b/tasks/mailcow__mailcow-dockerized-7300/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..abf399ff94ded28956773a8fe45fea0524b3c063 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7300/task.toml @@ -0,0 +1,71 @@ +version = "1.0" + +[task] +name = "trending/mailcow__mailcow-dockerized-7300" +description = "Update actions/checkout action to v7" + +[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 = "7e6c36dce1c106e95334410ad8313d1174fe15fa" +reference = "https://github.com/mailcow/mailcow-dockerized/pull/7300" +source_access = "auto" +built_at = "2026-11-16T16:09:53.178753+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:aabd1845c68b11f25cfa75fcbf60d517a7db420e0f82844b40f31425d5f45e7b" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-06-19T06:34:03Z" +diff_format = "unified" +context_files = [ + ".github/workflows/image_builds.yml", + ".github/workflows/pr_to_nightly.yml", + ".github/workflows/rebuild_backup_image.yml", + ".github/workflows/update_postscreen_access_list.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.459607+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:b20c70b991c670bc3c7877be9436e5223b7e5c7ee60c9d63446d7be41500c972" +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-7300/tests/capture.py b/tasks/mailcow__mailcow-dockerized-7300/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7300/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture 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-7300/tests/instruction.md b/tasks/mailcow__mailcow-dockerized-7300/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f40319e059710a6d5d0df7ffcab8fe2a666829d1 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7300/tests/instruction.md @@ -0,0 +1,74 @@ +# Issue + +**Title:** Update actions/checkout action to v7 + +## Description + +This PR contains the following updates: + +| Package | Type | Update | Change | +|---|---|---|---| +| [actions/checkout](https://redirect.github.com/actions/checkout) | action | major | `v6` → `v7` | + +--- + +### Release Notes + +
+actions/checkout (actions/checkout) + +### [`v7.0.0`](https://redirect.github.com/actions/checkout/blob/HEAD/CHANGELOG.md#v700) + +[Compare Source](https://redirect.github.com/actions/checkout/compare/v7.0.0...v7.0.0) + +- Block checking out fork PR for pull\_request\_target and workflow\_run by [@​aiqiaoy](https://redirect.github.com/aiqiaoy) in +- Bump actions/publish-immutable-action from 0.0.3 to 0.0.4 in the minor-actions-dependencies group across 1 directory by [@​dependabot](https://redirect.github.com/dependabot)\[bot] in +- Bump flatted from 3.3.1 to 3.4.2 by [@​dependabot](https://redirect.github.com/dependabot)\[bot] in +- Bump js-yaml from 4.1.0 to 4.2.0 by [@​dependabot](https://redirect.github.com/dependabot)\[bot] in +- Bump [@​actions/core](https://redirect.github.com/actions/core) and [@​actions/tool-cache](https://redirect.github.com/actions/tool-cache) and Remove uuid by [@​dependabot](https://redirect.github.com/dependabot)\[bot] in +- upgrade module to esm and update dependencies by [@​aiqiaoy](https://redirect.github.com/aiqiaoy) in +- Bump the minor-npm-dependencies group across 1 directory with 3 updates by [@​dependabot](https://redirect.github.com/dependabot)\[bot] in + +### [`v7`](https://redirect.github.com/actions/checkout/blob/HEAD/CHANGELOG.md#v700) + +[Compare Source](https://redirect.github.com/actions/checkout/compare/v6.0.3...v7.0.0) + +- Block checking out fork PR for pull\_request\_target and workflow\_run by [@​aiqiaoy](https://redirect.github.com/aiqiaoy) in +- Bump actions/publish-immutable-action from 0.0.3 to 0.0.4 in the minor-actions-dependencies group across 1 directory by [@​dependabot](https://redirect.github.com/dependabot)\[bot] in +- Bump flatted from 3.3.1 to 3.4.2 by [@​dependabot](https://redirect.github.com/dependabot)\[bot] in +- Bump js-yaml from 4.1.0 to 4.2.0 by [@​dependabot](https://redirect.github.com/dependabot)\[bot] in +- Bump [@​actions/core](https://redirect.github.com/actions/core) and [@​actions/tool-cache](https://redirect.github.com/actions/tool-cache) and Remove uuid by [@​dependabot](https://redirect.github.com/dependabot)\[bot] in +- upgrade module to esm and update dependencies by [@​aiqiaoy](https://redirect.github.com/aiqiaoy) in +- Bump the minor-npm-dependencies group across 1 directory with 3 updates by [@​dependabot](https://redirect.github.com/dependabot)\[bot] in + +
+ +--- + +### Configuration + +📅 **Schedule**: (in timezone Europe/Berlin) + +- Branch creation + - At any time (no schedule defined) +- Automerge + - At any time (no schedule defined) + +🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied. + +♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox. + +🔕 **Ignore**: Close this PR and you won't be reminded about this update again. + +--- + + - [ ] If you want to rebase/retry this PR, check this box + +--- + +This PR was generated by [Mend Renovate](https://mend.io/renovate/). View the [repository job log](https://developer.mend.io/github/mailcow/mailcow-dockerized). + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `7e6c36dce1c1`. Edit files in place; the verifier captures your changes via `git diff` 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-7300/tests/oracle.patch b/tasks/mailcow__mailcow-dockerized-7300/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..cad0067cb10f101eade1bb4f358734432f94ee2f --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7300/tests/oracle.patch @@ -0,0 +1,52 @@ +diff --git a/.github/workflows/image_builds.yml b/.github/workflows/image_builds.yml +index c8ec7cca..aa56b038 100644 +--- a/.github/workflows/image_builds.yml ++++ b/.github/workflows/image_builds.yml +@@ -27,7 +27,7 @@ jobs: + - "watchdog-mailcow" + runs-on: ubuntu-latest + steps: +- - uses: actions/checkout@v6 ++ - uses: actions/checkout@v7 + - name: Setup Docker + run: | + curl -sSL https://get.docker.com/ | CHANNEL=stable sudo sh +diff --git a/.github/workflows/pr_to_nightly.yml b/.github/workflows/pr_to_nightly.yml +index 01d7a91a..5c361af7 100644 +--- a/.github/workflows/pr_to_nightly.yml ++++ b/.github/workflows/pr_to_nightly.yml +@@ -8,7 +8,7 @@ jobs: + runs-on: ubuntu-latest + steps: + - name: Checkout repository +- uses: actions/checkout@v6 ++ uses: actions/checkout@v7 + with: + fetch-depth: 0 + - name: Run the Action +diff --git a/.github/workflows/rebuild_backup_image.yml b/.github/workflows/rebuild_backup_image.yml +index b18d339b..4490afee 100644 +--- a/.github/workflows/rebuild_backup_image.yml ++++ b/.github/workflows/rebuild_backup_image.yml +@@ -13,7 +13,7 @@ jobs: + packages: write + steps: + - name: Checkout +- uses: actions/checkout@v6 ++ uses: actions/checkout@v7 + + - name: Set up QEMU + uses: docker/setup-qemu-action@v4 +diff --git a/.github/workflows/update_postscreen_access_list.yml b/.github/workflows/update_postscreen_access_list.yml +index 066616ae..ed63281c 100644 +--- a/.github/workflows/update_postscreen_access_list.yml ++++ b/.github/workflows/update_postscreen_access_list.yml +@@ -15,7 +15,7 @@ jobs: + runs-on: ubuntu-latest + steps: + - name: Checkout +- uses: actions/checkout@v6 ++ uses: actions/checkout@v7 + + - name: Generate postscreen_access.cidr + run: | diff --git a/tasks/mailcow__mailcow-dockerized-7300/tests/test.sh b/tasks/mailcow__mailcow-dockerized-7300/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..62e1a88972f28163918336195f3e499d68c10c09 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7300/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 7e6c36dce1c106e95334410ad8313d1174fe15fa > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "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-7300/tests/verifier.py b/tasks/mailcow__mailcow-dockerized-7300/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7300/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "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-7302/environment/Dockerfile b/tasks/mailcow__mailcow-dockerized-7302/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..941f4442a49f830b2f4faa650a378b62beefae0c --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7302/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git 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 47e4552b44ddfd528b99987545ccdaf61135f2c9 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 47e4552b44ddfd528b99987545ccdaf61135f2c9 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 47e4552b44ddfd528b99987545ccdaf61135f2c9 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -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-7302/instruction.md b/tasks/mailcow__mailcow-dockerized-7302/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e432f37e079ca3ff8e560692de74a0fb15431575 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7302/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 `47e4552b44dd`. Edit files in place; the verifier captures your changes via `git diff` 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-7302/solution/patch.diff b/tasks/mailcow__mailcow-dockerized-7302/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..63bc0bf52bf6042a2037b2b5428b50e73c05f3c1 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7302/solution/patch.diff @@ -0,0 +1,83 @@ +diff --git a/data/web/lang/lang.fr-fr.json b/data/web/lang/lang.fr-fr.json +index 43c9c065..9ee91671 100644 +--- a/data/web/lang/lang.fr-fr.json ++++ b/data/web/lang/lang.fr-fr.json +@@ -111,7 +111,8 @@ + "app_passwd_protocols": "Protocoles autorisés pour le mot de passe de l'application", + "dry": "Simuler la synchronisation", + "internal": "Interne", +- "internal_info": "Les alias internes sont accessibles uniquement depuis le domaine ou les alias du domaine." ++ "internal_info": "Les alias internes sont accessibles uniquement depuis le domaine ou les alias du domaine.", ++ "sender_allowed": "Autoriser l'envoi sous cet alias" + }, + "admin": { + "access": "Accès", +@@ -556,7 +557,9 @@ + "max_age_invalid": "L'âge maximum %s est invalide", + "mode_invalid": "Le mode %s est invalide", + "mx_invalid": "L'enregistrement MX %s est invalide", +- "version_invalid": "La version %s est invalide" ++ "version_invalid": "La version %s est invalide", ++ "tfa_removal_blocked": "L’authentification à deux facteurs ne peut pas être supprimée, car elle est requise pour votre compte.", ++ "quarantine_category_invalid": "La catégorie de quarantaine doit être l’une des suivantes : add_header, reject, all\"" + }, + "debug": { + "chart_this_server": "Graphique (ce serveur)", +@@ -755,7 +758,9 @@ + "mta_sts_info": "MTA-STS est un standard qui oblige la délivrance des courriels entre les serveurs de courriels à utiliser TLS avec des certificats valides.
Il est utilisé quand DANE n'est pas possible à cause d'un manque ou d'un non support de DNSSEC.
Note : Si le domaine du destinataire supporte DANE avec DNSSEC, DANE est toujours préféré – MTA-STS sert seulement en secours.", + "mta_sts_mode_info": "Il y a trois modes parmi lesquels choisir :
  • testing – la politique est seulement surveillée, les violations n'ont pas d'impact.
  • enforce – la politique est appliquée strictement, les connexions sans TLS valide sont rejetées.
  • none – la politique est publiée mais non appliquée.
", + "mta_sts_max_age_info": "Durée en secondes pendant laquelle les serveurs de courriel peuvent mettre en cache cette politique avant de revérifier.", +- "mta_sts_mx_info": "Autoriser l'envoi uniquement aux noms d'hôtes des serveurs de courriels indiqués explicitement ; le MTA émetteur vérifie si le nom d'hôte DNS du MX correspond à la liste de la politique, et autorise la délivrance seulement avec un certificat TLS valide (protège contre le MITM)." ++ "mta_sts_mx_info": "Autoriser l'envoi uniquement aux noms d'hôtes des serveurs de courriels indiqués explicitement ; le MTA émetteur vérifie si le nom d'hôte DNS du MX correspond à la liste de la politique, et autorise la délivrance seulement avec un certificat TLS valide (protège contre le MITM).", ++ "sender_allowed": "Autoriser l'envoi sous cet alias", ++ "sender_allowed_info": "Si cette option est désactivée, cet alias peut uniquement recevoir des courriels. Utilisez les ACL d’expéditeur pour autoriser certaines boîtes aux lettres à envoyer des messages via cet alias." + }, + "footer": { + "cancel": "Annuler", +@@ -988,7 +993,8 @@ + "recipient": "Destinataire", + "open_logs": "Afficher les journaux", + "iam": "Fournisseur d'identité", +- "internal": "Interne" ++ "internal": "Interne", ++ "force_tfa": "TFA" + }, + "oauth2": { + "access_denied": "Veuillez vous connecter en tant que propriétaire de la boîte de réception pour accorder l’accès via Oauth2.", +@@ -1189,7 +1195,11 @@ + "yubi_otp": "Authentification OTP Yubico", + "authenticators": "Authentificateurs", + "u2f_deprecated_important": "Veuillez enregistrer votre clé dans le panneau d'administration avec la nouvelle méthode WebAuthn.", +- "u2f_deprecated": "Il semble que votre clé ait été enregistrée à l'aide de la méthode U2F obsolète. Nous allons désactiver l'authentification à deux facteurs pour vous et supprimer votre clé." ++ "u2f_deprecated": "Il semble que votre clé ait été enregistrée à l'aide de la méthode U2F obsolète. Nous allons désactiver l'authentification à deux facteurs pour vous et supprimer votre clé.", ++ "force_tfa": "Imposer l'authentification à deux facteurs lors de la connexion", ++ "force_tfa_info": "L’utilisateur doit configurer l’authentification à deux facteurs avant de pouvoir accéder à l’interface.", ++ "setup_title": "Authentification à deux facteurs requise", ++ "setup_required": "Votre compte nécessite l’authentification à deux facteurs. Veuillez configurer une méthode 2FA pour continuer." + }, + "fido2": { + "set_fn": "Définir un nom", +@@ -1378,7 +1388,8 @@ + "forever": "Pour toujours", + "spam_aliases_info": "Un alias de spam est une adresse de courriel temporaire qui peut être utilisée pour protéger les véritables adresses de courriel.
De manière optionnelle, une durée d'expiration peut être définie afin que l'alias soit automatiquement désactivé après la période définie, éliminant ainsi les adresses étant abusées ou ayant fuité.", + "authentication": "Authentification", +- "protocols": "Protocoles" ++ "protocols": "Protocoles", ++ "pw_update_required": "Votre compte nécessite un changement de mot de passe. Veuillez définir un nouveau mot de passe pour continuer." + }, + "warning": { + "cannot_delete_self": "Impossible de supprimer l’utilisateur connecté", +diff --git a/data/web/lang/lang.si-si.json b/data/web/lang/lang.si-si.json +index f5ba53f9..39d57eb3 100644 +--- a/data/web/lang/lang.si-si.json ++++ b/data/web/lang/lang.si-si.json +@@ -1001,7 +1001,8 @@ + "weekly": "Tedensko", + "sieve_info": "Na uporabnika lahko shranite več filtrov, vendar je lahko hkrati aktiven le en predfilter in en postfilter.
\nVsak filter bo obdelan v opisanem vrstnem redu. Niti neuspešen skript niti izdan ukaz »keep;« ne bosta ustavila obdelave nadaljnjih skript. Spremembe globalnih skriptov sita bodo sprožile ponovni zagon Dovecota.

Globalni predfilter sita • Predfilter • Uporabniški skripti • Postfilter • Globalni postfilter sita", + "tls_policy_maps_info": "Ta preslikava pravilnikov preglasi pravila odhodnega prenosa TLS neodvisno od uporabnikovih nastavitev pravilnikov TLS.
\n Za več informacij preverite dokumentacijo »smtp_tls_policy_maps«.", +- "internal": "Notranje" ++ "internal": "Notranje", ++ "force_tfa": "TFA" + }, + "fido2": { + "known_ids": "Znani ID-ji", diff --git a/tasks/mailcow__mailcow-dockerized-7302/solution/solve.sh b/tasks/mailcow__mailcow-dockerized-7302/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7302/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo 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-7302/task.toml b/tasks/mailcow__mailcow-dockerized-7302/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..52dc616ce794c08a47328567f738792838bb40b6 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7302/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/mailcow__mailcow-dockerized-7302" +description = "Translations update from Weblate" + +[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 = "47e4552b44ddfd528b99987545ccdaf61135f2c9" +reference = "https://github.com/mailcow/mailcow-dockerized/pull/7302" +source_access = "auto" +built_at = "2026-11-16T16:09:53.161613+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:68c34170ee2aa5b0d74c50eac098259b8006337801e66a47c22fe77e9124f820" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-06-20T11:57:15Z" +diff_format = "unified" +context_files = [ + "data/web/lang/lang.fr-fr.json", + "data/web/lang/lang.si-si.json", +] +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.460115+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:f831e085353c5c79202a7d6366dca8f819dc35b2d49511dbd4ecdecc468bf5e1" +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-7302/tests/capture.py b/tasks/mailcow__mailcow-dockerized-7302/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7302/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture 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-7302/tests/instruction.md b/tasks/mailcow__mailcow-dockerized-7302/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e432f37e079ca3ff8e560692de74a0fb15431575 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7302/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 `47e4552b44dd`. Edit files in place; the verifier captures your changes via `git diff` 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-7302/tests/oracle.patch b/tasks/mailcow__mailcow-dockerized-7302/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..63bc0bf52bf6042a2037b2b5428b50e73c05f3c1 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7302/tests/oracle.patch @@ -0,0 +1,83 @@ +diff --git a/data/web/lang/lang.fr-fr.json b/data/web/lang/lang.fr-fr.json +index 43c9c065..9ee91671 100644 +--- a/data/web/lang/lang.fr-fr.json ++++ b/data/web/lang/lang.fr-fr.json +@@ -111,7 +111,8 @@ + "app_passwd_protocols": "Protocoles autorisés pour le mot de passe de l'application", + "dry": "Simuler la synchronisation", + "internal": "Interne", +- "internal_info": "Les alias internes sont accessibles uniquement depuis le domaine ou les alias du domaine." ++ "internal_info": "Les alias internes sont accessibles uniquement depuis le domaine ou les alias du domaine.", ++ "sender_allowed": "Autoriser l'envoi sous cet alias" + }, + "admin": { + "access": "Accès", +@@ -556,7 +557,9 @@ + "max_age_invalid": "L'âge maximum %s est invalide", + "mode_invalid": "Le mode %s est invalide", + "mx_invalid": "L'enregistrement MX %s est invalide", +- "version_invalid": "La version %s est invalide" ++ "version_invalid": "La version %s est invalide", ++ "tfa_removal_blocked": "L’authentification à deux facteurs ne peut pas être supprimée, car elle est requise pour votre compte.", ++ "quarantine_category_invalid": "La catégorie de quarantaine doit être l’une des suivantes : add_header, reject, all\"" + }, + "debug": { + "chart_this_server": "Graphique (ce serveur)", +@@ -755,7 +758,9 @@ + "mta_sts_info": "MTA-STS est un standard qui oblige la délivrance des courriels entre les serveurs de courriels à utiliser TLS avec des certificats valides.
Il est utilisé quand DANE n'est pas possible à cause d'un manque ou d'un non support de DNSSEC.
Note : Si le domaine du destinataire supporte DANE avec DNSSEC, DANE est toujours préféré – MTA-STS sert seulement en secours.", + "mta_sts_mode_info": "Il y a trois modes parmi lesquels choisir :
  • testing – la politique est seulement surveillée, les violations n'ont pas d'impact.
  • enforce – la politique est appliquée strictement, les connexions sans TLS valide sont rejetées.
  • none – la politique est publiée mais non appliquée.
", + "mta_sts_max_age_info": "Durée en secondes pendant laquelle les serveurs de courriel peuvent mettre en cache cette politique avant de revérifier.", +- "mta_sts_mx_info": "Autoriser l'envoi uniquement aux noms d'hôtes des serveurs de courriels indiqués explicitement ; le MTA émetteur vérifie si le nom d'hôte DNS du MX correspond à la liste de la politique, et autorise la délivrance seulement avec un certificat TLS valide (protège contre le MITM)." ++ "mta_sts_mx_info": "Autoriser l'envoi uniquement aux noms d'hôtes des serveurs de courriels indiqués explicitement ; le MTA émetteur vérifie si le nom d'hôte DNS du MX correspond à la liste de la politique, et autorise la délivrance seulement avec un certificat TLS valide (protège contre le MITM).", ++ "sender_allowed": "Autoriser l'envoi sous cet alias", ++ "sender_allowed_info": "Si cette option est désactivée, cet alias peut uniquement recevoir des courriels. Utilisez les ACL d’expéditeur pour autoriser certaines boîtes aux lettres à envoyer des messages via cet alias." + }, + "footer": { + "cancel": "Annuler", +@@ -988,7 +993,8 @@ + "recipient": "Destinataire", + "open_logs": "Afficher les journaux", + "iam": "Fournisseur d'identité", +- "internal": "Interne" ++ "internal": "Interne", ++ "force_tfa": "TFA" + }, + "oauth2": { + "access_denied": "Veuillez vous connecter en tant que propriétaire de la boîte de réception pour accorder l’accès via Oauth2.", +@@ -1189,7 +1195,11 @@ + "yubi_otp": "Authentification OTP Yubico", + "authenticators": "Authentificateurs", + "u2f_deprecated_important": "Veuillez enregistrer votre clé dans le panneau d'administration avec la nouvelle méthode WebAuthn.", +- "u2f_deprecated": "Il semble que votre clé ait été enregistrée à l'aide de la méthode U2F obsolète. Nous allons désactiver l'authentification à deux facteurs pour vous et supprimer votre clé." ++ "u2f_deprecated": "Il semble que votre clé ait été enregistrée à l'aide de la méthode U2F obsolète. Nous allons désactiver l'authentification à deux facteurs pour vous et supprimer votre clé.", ++ "force_tfa": "Imposer l'authentification à deux facteurs lors de la connexion", ++ "force_tfa_info": "L’utilisateur doit configurer l’authentification à deux facteurs avant de pouvoir accéder à l’interface.", ++ "setup_title": "Authentification à deux facteurs requise", ++ "setup_required": "Votre compte nécessite l’authentification à deux facteurs. Veuillez configurer une méthode 2FA pour continuer." + }, + "fido2": { + "set_fn": "Définir un nom", +@@ -1378,7 +1388,8 @@ + "forever": "Pour toujours", + "spam_aliases_info": "Un alias de spam est une adresse de courriel temporaire qui peut être utilisée pour protéger les véritables adresses de courriel.
De manière optionnelle, une durée d'expiration peut être définie afin que l'alias soit automatiquement désactivé après la période définie, éliminant ainsi les adresses étant abusées ou ayant fuité.", + "authentication": "Authentification", +- "protocols": "Protocoles" ++ "protocols": "Protocoles", ++ "pw_update_required": "Votre compte nécessite un changement de mot de passe. Veuillez définir un nouveau mot de passe pour continuer." + }, + "warning": { + "cannot_delete_self": "Impossible de supprimer l’utilisateur connecté", +diff --git a/data/web/lang/lang.si-si.json b/data/web/lang/lang.si-si.json +index f5ba53f9..39d57eb3 100644 +--- a/data/web/lang/lang.si-si.json ++++ b/data/web/lang/lang.si-si.json +@@ -1001,7 +1001,8 @@ + "weekly": "Tedensko", + "sieve_info": "Na uporabnika lahko shranite več filtrov, vendar je lahko hkrati aktiven le en predfilter in en postfilter.
\nVsak filter bo obdelan v opisanem vrstnem redu. Niti neuspešen skript niti izdan ukaz »keep;« ne bosta ustavila obdelave nadaljnjih skript. Spremembe globalnih skriptov sita bodo sprožile ponovni zagon Dovecota.

Globalni predfilter sita • Predfilter • Uporabniški skripti • Postfilter • Globalni postfilter sita", + "tls_policy_maps_info": "Ta preslikava pravilnikov preglasi pravila odhodnega prenosa TLS neodvisno od uporabnikovih nastavitev pravilnikov TLS.
\n Za več informacij preverite dokumentacijo »smtp_tls_policy_maps«.", +- "internal": "Notranje" ++ "internal": "Notranje", ++ "force_tfa": "TFA" + }, + "fido2": { + "known_ids": "Znani ID-ji", diff --git a/tasks/mailcow__mailcow-dockerized-7302/tests/test.sh b/tasks/mailcow__mailcow-dockerized-7302/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..0b472fa8becede921037a8a2ae275565274ae06e --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7302/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 47e4552b44ddfd528b99987545ccdaf61135f2c9 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "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-7302/tests/verifier.py b/tasks/mailcow__mailcow-dockerized-7302/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7302/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "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-7305/environment/Dockerfile b/tasks/mailcow__mailcow-dockerized-7305/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b3b5fc5ee9b9524bdeafa62ead26a39e14a8ad71 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7305/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git 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 9e723e942d02de31ba8ca78aa5e34a68b62ed38b 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 9e723e942d02de31ba8ca78aa5e34a68b62ed38b \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 9e723e942d02de31ba8ca78aa5e34a68b62ed38b \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -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-7305/instruction.md b/tasks/mailcow__mailcow-dockerized-7305/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..85d02d2f10a857521e89cdcf9704476c5845339d --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7305/instruction.md @@ -0,0 +1,43 @@ +# Issue + +**Title:** [Nignx] Update to 1.30.3 + +## 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 +- + +This PR updates Nginx to 1.30.3 + +### Affected Containers + + + + + +- nginx-mailcow + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `9e723e942d02`. Edit files in place; the verifier captures your changes via `git diff` 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-7305/solution/patch.diff b/tasks/mailcow__mailcow-dockerized-7305/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..a3b651592f889a36f61658cf6af05464a7d8ae92 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7305/solution/patch.diff @@ -0,0 +1,23 @@ +diff --git a/data/Dockerfiles/nginx/Dockerfile b/data/Dockerfiles/nginx/Dockerfile +index 30297362..65b34838 100644 +--- a/data/Dockerfiles/nginx/Dockerfile ++++ b/data/Dockerfiles/nginx/Dockerfile +@@ -1,4 +1,4 @@ +-FROM nginx:1.30.2-alpine ++FROM nginx:1.30.3-alpine + LABEL maintainer "The Infrastructure Company GmbH " + + ENV PIP_BREAK_SYSTEM_PACKAGES=1 +diff --git a/docker-compose.yml b/docker-compose.yml +index cccf3a21..6f579a8a 100644 +--- a/docker-compose.yml ++++ b/docker-compose.yml +@@ -419,7 +419,7 @@ services: + - php-fpm-mailcow + - sogo-mailcow + - rspamd-mailcow +- image: ghcr.io/mailcow/nginx:1.30.2-1 ++ image: ghcr.io/mailcow/nginx:1.30.3-1 + dns: + - ${IPV4_NETWORK:-172.22.1}.254 + environment: diff --git a/tasks/mailcow__mailcow-dockerized-7305/solution/solve.sh b/tasks/mailcow__mailcow-dockerized-7305/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7305/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo 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-7305/task.toml b/tasks/mailcow__mailcow-dockerized-7305/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..4971bf1ab9c91bca1b74f528962fa585699f2f4d --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7305/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/mailcow__mailcow-dockerized-7305" +description = "[Nignx] Update to 1.30.3" + +[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 = "9e723e942d02de31ba8ca78aa5e34a68b62ed38b" +reference = "https://github.com/mailcow/mailcow-dockerized/pull/7305" +source_access = "auto" +built_at = "2026-11-16T16:09:53.164978+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:1190201402d21d985328d473174286060bf1590c059ad89328a95f4522a571ed" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-06-25T10:20:26Z" +diff_format = "unified" +context_files = [ + "data/Dockerfiles/nginx/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.460616+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:94e804240c22df22851584a4ed002bcff79a22dc6fc730e7c4d0d06f1bf9fc17" +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-7305/tests/capture.py b/tasks/mailcow__mailcow-dockerized-7305/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7305/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture 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-7305/tests/instruction.md b/tasks/mailcow__mailcow-dockerized-7305/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..85d02d2f10a857521e89cdcf9704476c5845339d --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7305/tests/instruction.md @@ -0,0 +1,43 @@ +# Issue + +**Title:** [Nignx] Update to 1.30.3 + +## 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 +- + +This PR updates Nginx to 1.30.3 + +### Affected Containers + + + + + +- nginx-mailcow + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `9e723e942d02`. Edit files in place; the verifier captures your changes via `git diff` 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-7305/tests/oracle.patch b/tasks/mailcow__mailcow-dockerized-7305/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..a3b651592f889a36f61658cf6af05464a7d8ae92 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7305/tests/oracle.patch @@ -0,0 +1,23 @@ +diff --git a/data/Dockerfiles/nginx/Dockerfile b/data/Dockerfiles/nginx/Dockerfile +index 30297362..65b34838 100644 +--- a/data/Dockerfiles/nginx/Dockerfile ++++ b/data/Dockerfiles/nginx/Dockerfile +@@ -1,4 +1,4 @@ +-FROM nginx:1.30.2-alpine ++FROM nginx:1.30.3-alpine + LABEL maintainer "The Infrastructure Company GmbH " + + ENV PIP_BREAK_SYSTEM_PACKAGES=1 +diff --git a/docker-compose.yml b/docker-compose.yml +index cccf3a21..6f579a8a 100644 +--- a/docker-compose.yml ++++ b/docker-compose.yml +@@ -419,7 +419,7 @@ services: + - php-fpm-mailcow + - sogo-mailcow + - rspamd-mailcow +- image: ghcr.io/mailcow/nginx:1.30.2-1 ++ image: ghcr.io/mailcow/nginx:1.30.3-1 + dns: + - ${IPV4_NETWORK:-172.22.1}.254 + environment: diff --git a/tasks/mailcow__mailcow-dockerized-7305/tests/test.sh b/tasks/mailcow__mailcow-dockerized-7305/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b60409b3a07e091ba9d6ca091ad14c440c45fbb2 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7305/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 9e723e942d02de31ba8ca78aa5e34a68b62ed38b > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "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-7305/tests/verifier.py b/tasks/mailcow__mailcow-dockerized-7305/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7305/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "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-7311/environment/Dockerfile b/tasks/mailcow__mailcow-dockerized-7311/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6b7103301a6300f93df99ae47e9e7f2892c905e7 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7311/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git 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 99768e16f535f20854990bc2b2f25ddbbe48e715 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 99768e16f535f20854990bc2b2f25ddbbe48e715 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 99768e16f535f20854990bc2b2f25ddbbe48e715 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -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-7311/instruction.md b/tasks/mailcow__mailcow-dockerized-7311/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..63dd08e75e22390a340a60509a1b115afa223d85 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7311/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 `99768e16f535`. Edit files in place; the verifier captures your changes via `git diff` 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-7311/solution/patch.diff b/tasks/mailcow__mailcow-dockerized-7311/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..74bbbd2ea8b291afdfcc2537dd74cbaaa4444302 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7311/solution/patch.diff @@ -0,0 +1,55 @@ +diff --git a/data/conf/postfix/postscreen_access.cidr b/data/conf/postfix/postscreen_access.cidr +index 70fd2651..6fcedff9 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 Mon Jun 1 00:52:17 UTC 2026 ++# Whitelist generated by Postwhite v3.4 on Wed Jul 1 00:51:20 UTC 2026 + # https://github.com/stevejenkins/postwhite/ +-# 2186 total rules ++# 2251 total rules + 2a00:1450:4000::/36 permit + 2a00:1450:4864::/56 permit + 2a01:111:f400::/48 permit +@@ -1528,7 +1528,7 @@ + 149.97.173.180 permit + 149.118.160.128/25 permit + 150.136.21.199 permit +-150.171.109.118 permit ++150.171.109.183 permit + 150.230.98.160 permit + 151.145.38.14 permit + 152.67.105.195 permit +@@ -1605,6 +1605,12 @@ + 164.152.25.241 permit + 164.177.132.168/30 permit + 165.1.100.0/25 permit ++165.173.128.0/24 permit ++165.173.180.0/24 permit ++165.173.180.250/31 permit ++165.173.182.0/24 permit ++165.173.182.250/31 permit ++165.173.189.205 permit + 166.78.68.0/22 permit + 166.78.68.221 permit + 166.78.69.169 permit +@@ -1651,6 +1657,7 @@ + 173.203.81.39 permit + 173.224.161.128/25 permit + 173.224.165.0/26 permit ++173.224.166.48/28 permit + 174.36.84.8/29 permit + 174.36.84.16/29 permit + 174.36.84.32/29 permit +@@ -2171,7 +2178,10 @@ + 2001:748:400:3301::4 permit + 2404:6800:4000::/36 permit + 2404:6800:4864::/56 permit +-2603:1061:14:40::1 permit ++2603:1061:14:1c2::1 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 + 2607:f8b0:4864::/56 permit + 2620:109:c003:104::/64 permit diff --git a/tasks/mailcow__mailcow-dockerized-7311/solution/solve.sh b/tasks/mailcow__mailcow-dockerized-7311/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7311/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo 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-7311/task.toml b/tasks/mailcow__mailcow-dockerized-7311/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..770fe97f7287e05a536b0fec3253bca5a3047be4 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7311/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/mailcow__mailcow-dockerized-7311" +description = "[Postfix] update postscreen_access.cidr" + +[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 = "99768e16f535f20854990bc2b2f25ddbbe48e715" +reference = "https://github.com/mailcow/mailcow-dockerized/pull/7311" +source_access = "auto" +built_at = "2026-11-16T16:09:53.163332+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:81c701ca238037f60c6770c97c6b5a988d3807f815ba6a232feddd8965f70a31" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-07-01T09:31:58Z" +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 = 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.461108+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:a9493c53728b89a662261c1205be64ee831e4fbcb73ec6cb8ba7a5316737acb0" +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-7311/tests/capture.py b/tasks/mailcow__mailcow-dockerized-7311/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7311/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture 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-7311/tests/instruction.md b/tasks/mailcow__mailcow-dockerized-7311/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..63dd08e75e22390a340a60509a1b115afa223d85 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7311/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 `99768e16f535`. Edit files in place; the verifier captures your changes via `git diff` 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-7311/tests/oracle.patch b/tasks/mailcow__mailcow-dockerized-7311/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..74bbbd2ea8b291afdfcc2537dd74cbaaa4444302 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7311/tests/oracle.patch @@ -0,0 +1,55 @@ +diff --git a/data/conf/postfix/postscreen_access.cidr b/data/conf/postfix/postscreen_access.cidr +index 70fd2651..6fcedff9 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 Mon Jun 1 00:52:17 UTC 2026 ++# Whitelist generated by Postwhite v3.4 on Wed Jul 1 00:51:20 UTC 2026 + # https://github.com/stevejenkins/postwhite/ +-# 2186 total rules ++# 2251 total rules + 2a00:1450:4000::/36 permit + 2a00:1450:4864::/56 permit + 2a01:111:f400::/48 permit +@@ -1528,7 +1528,7 @@ + 149.97.173.180 permit + 149.118.160.128/25 permit + 150.136.21.199 permit +-150.171.109.118 permit ++150.171.109.183 permit + 150.230.98.160 permit + 151.145.38.14 permit + 152.67.105.195 permit +@@ -1605,6 +1605,12 @@ + 164.152.25.241 permit + 164.177.132.168/30 permit + 165.1.100.0/25 permit ++165.173.128.0/24 permit ++165.173.180.0/24 permit ++165.173.180.250/31 permit ++165.173.182.0/24 permit ++165.173.182.250/31 permit ++165.173.189.205 permit + 166.78.68.0/22 permit + 166.78.68.221 permit + 166.78.69.169 permit +@@ -1651,6 +1657,7 @@ + 173.203.81.39 permit + 173.224.161.128/25 permit + 173.224.165.0/26 permit ++173.224.166.48/28 permit + 174.36.84.8/29 permit + 174.36.84.16/29 permit + 174.36.84.32/29 permit +@@ -2171,7 +2178,10 @@ + 2001:748:400:3301::4 permit + 2404:6800:4000::/36 permit + 2404:6800:4864::/56 permit +-2603:1061:14:40::1 permit ++2603:1061:14:1c2::1 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 + 2607:f8b0:4864::/56 permit + 2620:109:c003:104::/64 permit diff --git a/tasks/mailcow__mailcow-dockerized-7311/tests/test.sh b/tasks/mailcow__mailcow-dockerized-7311/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..cf174377ec7ebdb825a763f2ebedba0a4a23b709 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7311/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 99768e16f535f20854990bc2b2f25ddbbe48e715 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "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-7311/tests/verifier.py b/tasks/mailcow__mailcow-dockerized-7311/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7311/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "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-7326/environment/Dockerfile b/tasks/mailcow__mailcow-dockerized-7326/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..08107f451c01a176ed7e968aedc1bdec0aa7264d --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7326/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git 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 d65aa11870bcc5dbcac108f9452b148b2f4e700a 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard d65aa11870bcc5dbcac108f9452b148b2f4e700a \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base d65aa11870bcc5dbcac108f9452b148b2f4e700a \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -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-7326/instruction.md b/tasks/mailcow__mailcow-dockerized-7326/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9f9fcf61630a6d67778246cb502c5a355f39c723 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7326/instruction.md @@ -0,0 +1,32 @@ +# Issue + +**Title:** Refined wording for displaying of active settings on quarantine page. + +## 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? + +Refined wording for displaying of active settings on quarantine page. + + + +### Affected Containers + +- `mailcowdockerized-php-fpm-mailcow-1` + + +## Did you run tests? + +No tests were run. Can't set up a full dev environment right now. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d65aa11870bc`. Edit files in place; the verifier captures your changes via `git diff` 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-7326/solution/patch.diff b/tasks/mailcow__mailcow-dockerized-7326/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..45eb74691a977aa9b1debe43a0d47f0075a6b004 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7326/solution/patch.diff @@ -0,0 +1,26 @@ +diff --git a/data/web/lang/lang.de-de.json b/data/web/lang/lang.de-de.json +index 17277a03..c19eb209 100644 +--- a/data/web/lang/lang.de-de.json ++++ b/data/web/lang/lang.de-de.json +@@ -1086,7 +1086,7 @@ + "rspamd_result": "Rspamd-Ergebnis", + "sender": "Sender (SMTP)", + "sender_header": "Sender (\"From\"-Header)", +- "settings_info": "Maximale Anzahl der zurückgehaltenen E-Mails: %s
Maximale Größe einer zu speichernden E-Mail: %s MiB", ++ "settings_info": "Maximale Anzahl der zurückgehaltenen E-Mails (pro Mailbox): %s
Maximale Größe einer zu speichernden E-Mail: %s MiB", + "show_item": "Details", + "spam": "Spam", + "spam_score": "Bewertung", +diff --git a/data/web/lang/lang.en-gb.json b/data/web/lang/lang.en-gb.json +index d2412fbf..873d7b98 100644 +--- a/data/web/lang/lang.en-gb.json ++++ b/data/web/lang/lang.en-gb.json +@@ -1087,7 +1087,7 @@ + "rspamd_result": "Rspamd result", + "sender": "Sender (SMTP)", + "sender_header": "Sender (\"From\" header)", +- "settings_info": "Maximum amount of elements to be quarantined: %s
Maximum email size: %s MiB", ++ "settings_info": "Maximum amount of elements to be quarantined (per mailbox): %s
Maximum email size: %s MiB", + "show_item": "Show item", + "spam": "Spam", + "spam_score": "Score", diff --git a/tasks/mailcow__mailcow-dockerized-7326/solution/solve.sh b/tasks/mailcow__mailcow-dockerized-7326/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7326/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo 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-7326/task.toml b/tasks/mailcow__mailcow-dockerized-7326/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..a4602f5a96cb7ac51f312367c9930f1bf1069a14 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7326/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/mailcow__mailcow-dockerized-7326" +description = "Refined wording for displaying of active settings on quarantine page." + +[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 = "d65aa11870bcc5dbcac108f9452b148b2f4e700a" +reference = "https://github.com/mailcow/mailcow-dockerized/pull/7326" +source_access = "auto" +built_at = "2026-11-16T16:09:53.175608+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:2ec02e282683e26fa082abe4047e0d82f7445b8191b2984f60b4fa36aef94026" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-07-13T07:40:24Z" +diff_format = "unified" +context_files = [ + "data/web/lang/lang.de-de.json", + "data/web/lang/lang.en-gb.json", +] +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.461601+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:33872eeb97e2d61132f4bed1e406a761aa6cf73afd434a22c153823872167965" +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-7326/tests/capture.py b/tasks/mailcow__mailcow-dockerized-7326/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7326/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture 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-7326/tests/instruction.md b/tasks/mailcow__mailcow-dockerized-7326/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9f9fcf61630a6d67778246cb502c5a355f39c723 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7326/tests/instruction.md @@ -0,0 +1,32 @@ +# Issue + +**Title:** Refined wording for displaying of active settings on quarantine page. + +## 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? + +Refined wording for displaying of active settings on quarantine page. + + + +### Affected Containers + +- `mailcowdockerized-php-fpm-mailcow-1` + + +## Did you run tests? + +No tests were run. Can't set up a full dev environment right now. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d65aa11870bc`. Edit files in place; the verifier captures your changes via `git diff` 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-7326/tests/oracle.patch b/tasks/mailcow__mailcow-dockerized-7326/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..45eb74691a977aa9b1debe43a0d47f0075a6b004 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7326/tests/oracle.patch @@ -0,0 +1,26 @@ +diff --git a/data/web/lang/lang.de-de.json b/data/web/lang/lang.de-de.json +index 17277a03..c19eb209 100644 +--- a/data/web/lang/lang.de-de.json ++++ b/data/web/lang/lang.de-de.json +@@ -1086,7 +1086,7 @@ + "rspamd_result": "Rspamd-Ergebnis", + "sender": "Sender (SMTP)", + "sender_header": "Sender (\"From\"-Header)", +- "settings_info": "Maximale Anzahl der zurückgehaltenen E-Mails: %s
Maximale Größe einer zu speichernden E-Mail: %s MiB", ++ "settings_info": "Maximale Anzahl der zurückgehaltenen E-Mails (pro Mailbox): %s
Maximale Größe einer zu speichernden E-Mail: %s MiB", + "show_item": "Details", + "spam": "Spam", + "spam_score": "Bewertung", +diff --git a/data/web/lang/lang.en-gb.json b/data/web/lang/lang.en-gb.json +index d2412fbf..873d7b98 100644 +--- a/data/web/lang/lang.en-gb.json ++++ b/data/web/lang/lang.en-gb.json +@@ -1087,7 +1087,7 @@ + "rspamd_result": "Rspamd result", + "sender": "Sender (SMTP)", + "sender_header": "Sender (\"From\" header)", +- "settings_info": "Maximum amount of elements to be quarantined: %s
Maximum email size: %s MiB", ++ "settings_info": "Maximum amount of elements to be quarantined (per mailbox): %s
Maximum email size: %s MiB", + "show_item": "Show item", + "spam": "Spam", + "spam_score": "Score", diff --git a/tasks/mailcow__mailcow-dockerized-7326/tests/test.sh b/tasks/mailcow__mailcow-dockerized-7326/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..69ffe032c771e8401b9cabab60ab83c3eec52682 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7326/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace d65aa11870bcc5dbcac108f9452b148b2f4e700a > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "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-7326/tests/verifier.py b/tasks/mailcow__mailcow-dockerized-7326/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7326/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "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-7333/environment/Dockerfile b/tasks/mailcow__mailcow-dockerized-7333/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..3e32f6e491a60db1c785356a245a4e52b01f66ed --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7333/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git 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 c1d75cf808ab990f777f6cbc58c6bfdcdfc0dc49 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard c1d75cf808ab990f777f6cbc58c6bfdcdfc0dc49 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base c1d75cf808ab990f777f6cbc58c6bfdcdfc0dc49 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -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-7333/instruction.md b/tasks/mailcow__mailcow-dockerized-7333/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7f21f1781ecd2d495a234a5972cdfcff6c609a21 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7333/instruction.md @@ -0,0 +1,53 @@ +# Issue + +**Title:** fix: cors allowed origins settings validation + +## 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 + +. The CORS "Allowed Origins" setting (Configuration → Administrative Settings → CORS) validated each entry with `FILTER_VALIDATE_DOMAIN` / `FILTER_FLAG_HOSTNAME`, which only accepts bare hostnames (e.g. `example.com`). Per the Fetch/CORS spec, a browser's `Origin` header is always a full origin — `scheme://host[:port]` (e.g. `http://localhost:3000`) — never a bare hostname. Since the matching code in `cors('set_headers')` does an exact string comparison against `$_SERVER['HTTP_ORIGIN']`, a stored bare hostname could never match a real browser request, so the allowlist silently never worked for anything but the `*` wildcard. + +### Details + +This PR: +- Adds `valid_origin()` in `functions.inc.php`, which validates an entry is a well-formed origin: `http`/`https` scheme, a valid hostname or IP host (IPv6 bracket notation included), and no userinfo/path/query/fragment/trailing slash. +- Uses `valid_origin()` in `cors('edit')` instead of the bare-hostname check, so real origins like `http://localhost:3000` can now be saved. +- Normalizes accepted origins to lowercase before storing, since browsers always send a lowercase scheme/host in the `Origin` header (per the URL spec) — without this, an origin entered with any different casing would validate but then never match a real request. +- Updates the `edit`-path default (used when `allowed_origins` is omitted from the request, e.g. a partial API update) to build a full origin via the existing `getBaseURL()` helper instead of a bare hostname, so it still passes the stricter validation. +- Updates the `allowed_origins` example in `openapi.yaml` to a valid full origin. + + +### Affected Containers + +- php-fpm-mailcow +- nginx-mailcow + + +## Did you run tests? + +Yes + +### What did you test? + +Added a full origin (e.g. `http://localhost:3000`) to the CORS "Allowed Origins" setting, then called the mailcow API from a sample web app hosted on that origin. + + +### What were the final results? (Awaited, got) + +Awaited: the setting saves successfully and the cross-origin API request succeeds. +Got: success. the origin saved without error, and the request from the sample app succeeded. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `c1d75cf808ab`. Edit files in place; the verifier captures your changes via `git diff` 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-7333/solution/patch.diff b/tasks/mailcow__mailcow-dockerized-7333/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..bb8dfb1fc6e8ad5b8e259f940ea4b4d0f7eae9de --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7333/solution/patch.diff @@ -0,0 +1,83 @@ +diff --git a/data/web/api/openapi.yaml b/data/web/api/openapi.yaml +index 77c58b60..0aca6997 100644 +--- a/data/web/api/openapi.yaml ++++ b/data/web/api/openapi.yaml +@@ -5856,7 +5856,7 @@ paths: + response: + value: + - type: "success" +- log: ["cors", "edit", {"allowed_origins": ["*", "mail.mailcow.tld"], "allowed_methods": ["POST", "GET", "DELETE", "PUT"]}] ++ log: ["cors", "edit", {"allowed_origins": ["*", "https://mail.mailcow.tld"], "allowed_methods": ["POST", "GET", "DELETE", "PUT"]}] + msg: "cors_headers_edited" + description: OK + headers: { } +@@ -5873,7 +5873,7 @@ paths: + schema: + example: + attr: +- allowed_origins: ["*", "mail.mailcow.tld"] ++ allowed_origins: ["*", "https://mail.mailcow.tld"] + allowed_methods: ["POST", "GET", "DELETE", "PUT"] + properties: + attr: +diff --git a/data/web/inc/functions.inc.php b/data/web/inc/functions.inc.php +index 89f14b57..f9b0f6ab 100644 +--- a/data/web/inc/functions.inc.php ++++ b/data/web/inc/functions.inc.php +@@ -53,6 +53,28 @@ function valid_network($network) { + function valid_hostname($hostname) { + return filter_var($hostname, FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME); + } ++// Validates a browser-style Origin: scheme://host[:port], no path/query/fragment/credentials ++function valid_origin($origin) { ++ $parts = parse_url($origin); ++ if ($parts === false || !isset($parts['scheme']) || !isset($parts['host'])) { ++ return false; ++ } ++ if (!in_array(strtolower($parts['scheme']), array('http', 'https'), true)) { ++ return false; ++ } ++ if (isset($parts['user']) || isset($parts['pass']) || isset($parts['path']) || isset($parts['query']) || isset($parts['fragment'])) { ++ return false; ++ } ++ $host = $parts['host']; ++ $host_without_brackets = trim($host, '[]'); ++ if (!valid_hostname($host_without_brackets) && !filter_var($host_without_brackets, FILTER_VALIDATE_IP)) { ++ return false; ++ } ++ // Reject anything that doesn't round-trip to the exact same origin (e.g. stray trailing slash) ++ $port = isset($parts['port']) ? ':' . $parts['port'] : ''; ++ $rebuilt = strtolower($parts['scheme']) . '://' . strtolower($host) . $port; ++ return strtolower($origin) === $rebuilt; ++} + // Thanks to https://stackoverflow.com/a/49373789 + // Validates exact ip matches and ip-in-cidr, ipv4 and ipv6 + function ip_acl($ip, $networks) { +@@ -2283,10 +2305,13 @@ function cors($action, $data = null) { + return false; + } + +- $allowed_origins = isset($data['allowed_origins']) ? $data['allowed_origins'] : array($_SERVER['SERVER_NAME']); ++ $allowed_origins = isset($data['allowed_origins']) ? $data['allowed_origins'] : array(getBaseURL()); + $allowed_origins = !is_array($allowed_origins) ? array_filter(array_map('trim', explode("\n", $allowed_origins))) : $allowed_origins; +- foreach ($allowed_origins as $origin) { +- if (!filter_var($origin, FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME) && $origin != '*') { ++ foreach ($allowed_origins as &$origin) { ++ if ($origin === '*') { ++ continue; ++ } ++ if (!valid_origin($origin)) { + $_SESSION['return'][] = array( + 'type' => 'danger', + 'log' => array(__FUNCTION__, $action, $data), +@@ -2294,7 +2319,10 @@ function cors($action, $data = null) { + ); + return false; + } ++ // browsers always send a lowercase scheme/host in the Origin header, so normalize to match ++ $origin = strtolower($origin); + } ++ unset($origin); + + $allowed_methods = isset($data['allowed_methods']) ? $data['allowed_methods'] : array('GET', 'POST', 'PUT', 'DELETE'); + $allowed_methods = !is_array($allowed_methods) ? array_map('trim', preg_split( "/( |,|;|\n)/", $allowed_methods)) : $allowed_methods; diff --git a/tasks/mailcow__mailcow-dockerized-7333/solution/solve.sh b/tasks/mailcow__mailcow-dockerized-7333/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7333/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo 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-7333/task.toml b/tasks/mailcow__mailcow-dockerized-7333/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..dd6011ad3476aa55e77e7b8de2b8620829394d40 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7333/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/mailcow__mailcow-dockerized-7333" +description = "fix: cors allowed origins settings validation" + +[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 = "c1d75cf808ab990f777f6cbc58c6bfdcdfc0dc49" +reference = "https://github.com/mailcow/mailcow-dockerized/pull/7333" +source_access = "auto" +built_at = "2026-11-16T16:09:53.158150+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:8657831b99b95695eb06d629165a4746ffcf01ac1ca77a4305ad4dedc11d6db4" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-07-28T13:35:30Z" +diff_format = "unified" +context_files = [ + "data/web/api/openapi.yaml", + "data/web/inc/functions.inc.php", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 38 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.462101+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:1e9baf8599607c95669a26dabf592c84a746340e2ff8d795c6bee4261a69eeb8" +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-7333/tests/capture.py b/tasks/mailcow__mailcow-dockerized-7333/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7333/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture 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-7333/tests/instruction.md b/tasks/mailcow__mailcow-dockerized-7333/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7f21f1781ecd2d495a234a5972cdfcff6c609a21 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7333/tests/instruction.md @@ -0,0 +1,53 @@ +# Issue + +**Title:** fix: cors allowed origins settings validation + +## 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 + +. The CORS "Allowed Origins" setting (Configuration → Administrative Settings → CORS) validated each entry with `FILTER_VALIDATE_DOMAIN` / `FILTER_FLAG_HOSTNAME`, which only accepts bare hostnames (e.g. `example.com`). Per the Fetch/CORS spec, a browser's `Origin` header is always a full origin — `scheme://host[:port]` (e.g. `http://localhost:3000`) — never a bare hostname. Since the matching code in `cors('set_headers')` does an exact string comparison against `$_SERVER['HTTP_ORIGIN']`, a stored bare hostname could never match a real browser request, so the allowlist silently never worked for anything but the `*` wildcard. + +### Details + +This PR: +- Adds `valid_origin()` in `functions.inc.php`, which validates an entry is a well-formed origin: `http`/`https` scheme, a valid hostname or IP host (IPv6 bracket notation included), and no userinfo/path/query/fragment/trailing slash. +- Uses `valid_origin()` in `cors('edit')` instead of the bare-hostname check, so real origins like `http://localhost:3000` can now be saved. +- Normalizes accepted origins to lowercase before storing, since browsers always send a lowercase scheme/host in the `Origin` header (per the URL spec) — without this, an origin entered with any different casing would validate but then never match a real request. +- Updates the `edit`-path default (used when `allowed_origins` is omitted from the request, e.g. a partial API update) to build a full origin via the existing `getBaseURL()` helper instead of a bare hostname, so it still passes the stricter validation. +- Updates the `allowed_origins` example in `openapi.yaml` to a valid full origin. + + +### Affected Containers + +- php-fpm-mailcow +- nginx-mailcow + + +## Did you run tests? + +Yes + +### What did you test? + +Added a full origin (e.g. `http://localhost:3000`) to the CORS "Allowed Origins" setting, then called the mailcow API from a sample web app hosted on that origin. + + +### What were the final results? (Awaited, got) + +Awaited: the setting saves successfully and the cross-origin API request succeeds. +Got: success. the origin saved without error, and the request from the sample app succeeded. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `c1d75cf808ab`. Edit files in place; the verifier captures your changes via `git diff` 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-7333/tests/oracle.patch b/tasks/mailcow__mailcow-dockerized-7333/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..bb8dfb1fc6e8ad5b8e259f940ea4b4d0f7eae9de --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7333/tests/oracle.patch @@ -0,0 +1,83 @@ +diff --git a/data/web/api/openapi.yaml b/data/web/api/openapi.yaml +index 77c58b60..0aca6997 100644 +--- a/data/web/api/openapi.yaml ++++ b/data/web/api/openapi.yaml +@@ -5856,7 +5856,7 @@ paths: + response: + value: + - type: "success" +- log: ["cors", "edit", {"allowed_origins": ["*", "mail.mailcow.tld"], "allowed_methods": ["POST", "GET", "DELETE", "PUT"]}] ++ log: ["cors", "edit", {"allowed_origins": ["*", "https://mail.mailcow.tld"], "allowed_methods": ["POST", "GET", "DELETE", "PUT"]}] + msg: "cors_headers_edited" + description: OK + headers: { } +@@ -5873,7 +5873,7 @@ paths: + schema: + example: + attr: +- allowed_origins: ["*", "mail.mailcow.tld"] ++ allowed_origins: ["*", "https://mail.mailcow.tld"] + allowed_methods: ["POST", "GET", "DELETE", "PUT"] + properties: + attr: +diff --git a/data/web/inc/functions.inc.php b/data/web/inc/functions.inc.php +index 89f14b57..f9b0f6ab 100644 +--- a/data/web/inc/functions.inc.php ++++ b/data/web/inc/functions.inc.php +@@ -53,6 +53,28 @@ function valid_network($network) { + function valid_hostname($hostname) { + return filter_var($hostname, FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME); + } ++// Validates a browser-style Origin: scheme://host[:port], no path/query/fragment/credentials ++function valid_origin($origin) { ++ $parts = parse_url($origin); ++ if ($parts === false || !isset($parts['scheme']) || !isset($parts['host'])) { ++ return false; ++ } ++ if (!in_array(strtolower($parts['scheme']), array('http', 'https'), true)) { ++ return false; ++ } ++ if (isset($parts['user']) || isset($parts['pass']) || isset($parts['path']) || isset($parts['query']) || isset($parts['fragment'])) { ++ return false; ++ } ++ $host = $parts['host']; ++ $host_without_brackets = trim($host, '[]'); ++ if (!valid_hostname($host_without_brackets) && !filter_var($host_without_brackets, FILTER_VALIDATE_IP)) { ++ return false; ++ } ++ // Reject anything that doesn't round-trip to the exact same origin (e.g. stray trailing slash) ++ $port = isset($parts['port']) ? ':' . $parts['port'] : ''; ++ $rebuilt = strtolower($parts['scheme']) . '://' . strtolower($host) . $port; ++ return strtolower($origin) === $rebuilt; ++} + // Thanks to https://stackoverflow.com/a/49373789 + // Validates exact ip matches and ip-in-cidr, ipv4 and ipv6 + function ip_acl($ip, $networks) { +@@ -2283,10 +2305,13 @@ function cors($action, $data = null) { + return false; + } + +- $allowed_origins = isset($data['allowed_origins']) ? $data['allowed_origins'] : array($_SERVER['SERVER_NAME']); ++ $allowed_origins = isset($data['allowed_origins']) ? $data['allowed_origins'] : array(getBaseURL()); + $allowed_origins = !is_array($allowed_origins) ? array_filter(array_map('trim', explode("\n", $allowed_origins))) : $allowed_origins; +- foreach ($allowed_origins as $origin) { +- if (!filter_var($origin, FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME) && $origin != '*') { ++ foreach ($allowed_origins as &$origin) { ++ if ($origin === '*') { ++ continue; ++ } ++ if (!valid_origin($origin)) { + $_SESSION['return'][] = array( + 'type' => 'danger', + 'log' => array(__FUNCTION__, $action, $data), +@@ -2294,7 +2319,10 @@ function cors($action, $data = null) { + ); + return false; + } ++ // browsers always send a lowercase scheme/host in the Origin header, so normalize to match ++ $origin = strtolower($origin); + } ++ unset($origin); + + $allowed_methods = isset($data['allowed_methods']) ? $data['allowed_methods'] : array('GET', 'POST', 'PUT', 'DELETE'); + $allowed_methods = !is_array($allowed_methods) ? array_map('trim', preg_split( "/( |,|;|\n)/", $allowed_methods)) : $allowed_methods; diff --git a/tasks/mailcow__mailcow-dockerized-7333/tests/test.sh b/tasks/mailcow__mailcow-dockerized-7333/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..9e57ee9797434a904f9ccd59c8c9732c28345143 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7333/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace c1d75cf808ab990f777f6cbc58c6bfdcdfc0dc49 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "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-7333/tests/verifier.py b/tasks/mailcow__mailcow-dockerized-7333/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7333/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "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-7334/environment/Dockerfile b/tasks/mailcow__mailcow-dockerized-7334/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..3e32f6e491a60db1c785356a245a4e52b01f66ed --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7334/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git 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 c1d75cf808ab990f777f6cbc58c6bfdcdfc0dc49 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard c1d75cf808ab990f777f6cbc58c6bfdcdfc0dc49 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base c1d75cf808ab990f777f6cbc58c6bfdcdfc0dc49 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -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-7334/instruction.md b/tasks/mailcow__mailcow-dockerized-7334/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5483bacdb9f454a3ac56d6cf4803b2715f0334f1 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7334/instruction.md @@ -0,0 +1,46 @@ +# Issue + +**Title:** postfix-tlspol: upgrade to trixie + 1.11.0 update + +## 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 pull request updates the `postfix-tlspol` component and related configuration files to use newer versions of dependencies and images, and makes configuration changes to ensure compatibility with these updates. The main focus is on upgrading to version 1.11.0 of `postfix-tlspol` and updating related system and service configurations. + +**Dependency and Image Upgrades:** +- Updated the base images in the `Dockerfile` to use `golang:1.26-trixie` for building and `debian:trixie-slim` for runtime, and bumped the `postfix-tlspol` version to 1.11.0. +- Updated the `postfix-tlspol-mailcow` service in `docker-compose.yml` to use image version 1.11.0. + +**Configuration Updates for Compatibility:** +- Upgraded `syslog-ng` configuration files to version 4.8, and replaced the deprecated `stats_freq(0)` option with the new `stats(freq(0))` syntax in both `syslog-ng.conf` and `syslog-ng-redis_slave.conf`. [[1]](diffhunk://#diff-614528617a7a48101113f27e3d76258bbc95a0a941bce8effbce2b452d34e4fdL1-R1) [[2]](diffhunk://#diff-614528617a7a48101113f27e3d76258bbc95a0a941bce8effbce2b452d34e4fdL10-R10) [[3]](diffhunk://#diff-91d0a610f54c3b5914100c4481f81454d06ec891f0729a7e303b04ce139792e3L1-R1) [[4]](diffhunk://#diff-91d0a610f54c3b5914100c4481f81454d06ec891f0729a7e303b04ce139792e3L10-R10) +- Changed the `smtp_tls_policy_maps` setting in `postfix/main.cf` to use the `QUERYwithTLSRPT` socketmap, likely reflecting an updated query interface in the new version. + +### Affected Containers + +- postfix-mailcow +- postfix-tls-mailcow + +## Did you run tests? + +### What did you tested? + +General mailing + startups, as well as MTA-STS Lookups during mail sending. + +### What were the final results? (Awaited, got) + +Everything works as expected. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `c1d75cf808ab`. Edit files in place; the verifier captures your changes via `git diff` 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-7334/solution/patch.diff b/tasks/mailcow__mailcow-dockerized-7334/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..3aee23b6d4f61f29b39d086dcacd36aaaf008113 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7334/solution/patch.diff @@ -0,0 +1,89 @@ +diff --git a/data/Dockerfiles/postfix-tlspol/Dockerfile b/data/Dockerfiles/postfix-tlspol/Dockerfile +index 68f6ecce..fa363845 100644 +--- a/data/Dockerfiles/postfix-tlspol/Dockerfile ++++ b/data/Dockerfiles/postfix-tlspol/Dockerfile +@@ -1,17 +1,17 @@ +-FROM golang:1.25-bookworm AS builder ++FROM golang:1.26-trixie AS builder + WORKDIR /src + + ENV CGO_ENABLED=0 \ + GO111MODULE=on \ + NOOPT=1 \ +- VERSION=1.8.22 ++ VERSION=1.11.0 + + RUN git clone --branch v${VERSION} https://github.com/Zuplu/postfix-tlspol && \ + cd /src/postfix-tlspol && \ + scripts/build.sh build-only + + +-FROM debian:bookworm-slim ++FROM debian:trixie-slim + LABEL maintainer="The Infrastructure Company GmbH " + + ARG DEBIAN_FRONTEND=noninteractive +diff --git a/data/Dockerfiles/postfix-tlspol/syslog-ng-redis_slave.conf b/data/Dockerfiles/postfix-tlspol/syslog-ng-redis_slave.conf +index 3862a354..022dfc3d 100644 +--- a/data/Dockerfiles/postfix-tlspol/syslog-ng-redis_slave.conf ++++ b/data/Dockerfiles/postfix-tlspol/syslog-ng-redis_slave.conf +@@ -1,4 +1,4 @@ +-@version: 3.38 ++@version: 4.8 + @include "scl.conf" + options { + chain_hostnames(off); +@@ -7,7 +7,7 @@ options { + dns_cache(no); + use_fqdn(no); + owner("root"); group("adm"); perm(0640); +- stats_freq(0); ++ stats(freq(0)); + bad_hostname("^gconfd$"); + }; + source s_src { +diff --git a/data/Dockerfiles/postfix-tlspol/syslog-ng.conf b/data/Dockerfiles/postfix-tlspol/syslog-ng.conf +index 7126c125..70c92b5c 100644 +--- a/data/Dockerfiles/postfix-tlspol/syslog-ng.conf ++++ b/data/Dockerfiles/postfix-tlspol/syslog-ng.conf +@@ -1,4 +1,4 @@ +-@version: 3.38 ++@version: 4.8 + @include "scl.conf" + options { + chain_hostnames(off); +@@ -7,7 +7,7 @@ options { + dns_cache(no); + use_fqdn(no); + owner("root"); group("adm"); perm(0640); +- stats_freq(0); ++ stats(freq(0)); + bad_hostname("^gconfd$"); + }; + source s_src { +diff --git a/data/conf/postfix/main.cf b/data/conf/postfix/main.cf +index 080be499..4329f548 100644 +--- a/data/conf/postfix/main.cf ++++ b/data/conf/postfix/main.cf +@@ -150,7 +150,7 @@ smtp_sasl_auth_enable = yes + smtp_sasl_password_maps = proxy:mysql:/opt/postfix/conf/sql/mysql_sasl_passwd_maps_sender_dependent.cf + smtp_sasl_security_options = + smtp_sasl_mechanism_filter = plain, login +-smtp_tls_policy_maps = proxy:mysql:/opt/postfix/conf/sql/mysql_tls_policy_override_maps.cf socketmap:inet:postfix-tlspol:8642:QUERY ++smtp_tls_policy_maps = proxy:mysql:/opt/postfix/conf/sql/mysql_tls_policy_override_maps.cf socketmap:inet:postfix-tlspol:8642:QUERYwithTLSRPT + smtp_header_checks = pcre:/opt/postfix/conf/anonymize_headers.pcre + mail_name = Postcow + # local_transport map catches local destinations and prevents routing local dests when the next map would route "*" +diff --git a/docker-compose.yml b/docker-compose.yml +index 30a7ba96..b3cb8bef 100644 +--- a/docker-compose.yml ++++ b/docker-compose.yml +@@ -382,7 +382,7 @@ services: + - postfix + + postfix-tlspol-mailcow: +- image: ghcr.io/mailcow/postfix-tlspol:1.8.23 ++ image: ghcr.io/mailcow/postfix-tlspol:1.11.0 + depends_on: + unbound-mailcow: + condition: service_healthy diff --git a/tasks/mailcow__mailcow-dockerized-7334/solution/solve.sh b/tasks/mailcow__mailcow-dockerized-7334/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7334/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo 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-7334/task.toml b/tasks/mailcow__mailcow-dockerized-7334/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..43fe974d95418a6e80ecaf2bfb292b296230757d --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7334/task.toml @@ -0,0 +1,72 @@ +version = "1.0" + +[task] +name = "trending/mailcow__mailcow-dockerized-7334" +description = "postfix-tlspol: upgrade to trixie + 1.11.0 update" + +[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 = "c1d75cf808ab990f777f6cbc58c6bfdcdfc0dc49" +reference = "https://github.com/mailcow/mailcow-dockerized/pull/7334" +source_access = "auto" +built_at = "2026-11-16T16:09:53.153711+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:11929895475497c7e626f35aba1b87a9f8e1e51571d5eddc09e9fbb1a26861ee" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-08-18T11:20:16Z" +diff_format = "unified" +context_files = [ + "data/Dockerfiles/postfix-tlspol/Dockerfile", + "data/Dockerfiles/postfix-tlspol/syslog-ng-redis_slave.conf", + "data/Dockerfiles/postfix-tlspol/syslog-ng.conf", + "data/conf/postfix/main.cf", + "docker-compose.yml", +] +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.462602+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:1e9baf8599607c95669a26dabf592c84a746340e2ff8d795c6bee4261a69eeb8" +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-7334/tests/capture.py b/tasks/mailcow__mailcow-dockerized-7334/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7334/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture 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-7334/tests/instruction.md b/tasks/mailcow__mailcow-dockerized-7334/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5483bacdb9f454a3ac56d6cf4803b2715f0334f1 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7334/tests/instruction.md @@ -0,0 +1,46 @@ +# Issue + +**Title:** postfix-tlspol: upgrade to trixie + 1.11.0 update + +## 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 pull request updates the `postfix-tlspol` component and related configuration files to use newer versions of dependencies and images, and makes configuration changes to ensure compatibility with these updates. The main focus is on upgrading to version 1.11.0 of `postfix-tlspol` and updating related system and service configurations. + +**Dependency and Image Upgrades:** +- Updated the base images in the `Dockerfile` to use `golang:1.26-trixie` for building and `debian:trixie-slim` for runtime, and bumped the `postfix-tlspol` version to 1.11.0. +- Updated the `postfix-tlspol-mailcow` service in `docker-compose.yml` to use image version 1.11.0. + +**Configuration Updates for Compatibility:** +- Upgraded `syslog-ng` configuration files to version 4.8, and replaced the deprecated `stats_freq(0)` option with the new `stats(freq(0))` syntax in both `syslog-ng.conf` and `syslog-ng-redis_slave.conf`. [[1]](diffhunk://#diff-614528617a7a48101113f27e3d76258bbc95a0a941bce8effbce2b452d34e4fdL1-R1) [[2]](diffhunk://#diff-614528617a7a48101113f27e3d76258bbc95a0a941bce8effbce2b452d34e4fdL10-R10) [[3]](diffhunk://#diff-91d0a610f54c3b5914100c4481f81454d06ec891f0729a7e303b04ce139792e3L1-R1) [[4]](diffhunk://#diff-91d0a610f54c3b5914100c4481f81454d06ec891f0729a7e303b04ce139792e3L10-R10) +- Changed the `smtp_tls_policy_maps` setting in `postfix/main.cf` to use the `QUERYwithTLSRPT` socketmap, likely reflecting an updated query interface in the new version. + +### Affected Containers + +- postfix-mailcow +- postfix-tls-mailcow + +## Did you run tests? + +### What did you tested? + +General mailing + startups, as well as MTA-STS Lookups during mail sending. + +### What were the final results? (Awaited, got) + +Everything works as expected. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `c1d75cf808ab`. Edit files in place; the verifier captures your changes via `git diff` 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-7334/tests/oracle.patch b/tasks/mailcow__mailcow-dockerized-7334/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..3aee23b6d4f61f29b39d086dcacd36aaaf008113 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7334/tests/oracle.patch @@ -0,0 +1,89 @@ +diff --git a/data/Dockerfiles/postfix-tlspol/Dockerfile b/data/Dockerfiles/postfix-tlspol/Dockerfile +index 68f6ecce..fa363845 100644 +--- a/data/Dockerfiles/postfix-tlspol/Dockerfile ++++ b/data/Dockerfiles/postfix-tlspol/Dockerfile +@@ -1,17 +1,17 @@ +-FROM golang:1.25-bookworm AS builder ++FROM golang:1.26-trixie AS builder + WORKDIR /src + + ENV CGO_ENABLED=0 \ + GO111MODULE=on \ + NOOPT=1 \ +- VERSION=1.8.22 ++ VERSION=1.11.0 + + RUN git clone --branch v${VERSION} https://github.com/Zuplu/postfix-tlspol && \ + cd /src/postfix-tlspol && \ + scripts/build.sh build-only + + +-FROM debian:bookworm-slim ++FROM debian:trixie-slim + LABEL maintainer="The Infrastructure Company GmbH " + + ARG DEBIAN_FRONTEND=noninteractive +diff --git a/data/Dockerfiles/postfix-tlspol/syslog-ng-redis_slave.conf b/data/Dockerfiles/postfix-tlspol/syslog-ng-redis_slave.conf +index 3862a354..022dfc3d 100644 +--- a/data/Dockerfiles/postfix-tlspol/syslog-ng-redis_slave.conf ++++ b/data/Dockerfiles/postfix-tlspol/syslog-ng-redis_slave.conf +@@ -1,4 +1,4 @@ +-@version: 3.38 ++@version: 4.8 + @include "scl.conf" + options { + chain_hostnames(off); +@@ -7,7 +7,7 @@ options { + dns_cache(no); + use_fqdn(no); + owner("root"); group("adm"); perm(0640); +- stats_freq(0); ++ stats(freq(0)); + bad_hostname("^gconfd$"); + }; + source s_src { +diff --git a/data/Dockerfiles/postfix-tlspol/syslog-ng.conf b/data/Dockerfiles/postfix-tlspol/syslog-ng.conf +index 7126c125..70c92b5c 100644 +--- a/data/Dockerfiles/postfix-tlspol/syslog-ng.conf ++++ b/data/Dockerfiles/postfix-tlspol/syslog-ng.conf +@@ -1,4 +1,4 @@ +-@version: 3.38 ++@version: 4.8 + @include "scl.conf" + options { + chain_hostnames(off); +@@ -7,7 +7,7 @@ options { + dns_cache(no); + use_fqdn(no); + owner("root"); group("adm"); perm(0640); +- stats_freq(0); ++ stats(freq(0)); + bad_hostname("^gconfd$"); + }; + source s_src { +diff --git a/data/conf/postfix/main.cf b/data/conf/postfix/main.cf +index 080be499..4329f548 100644 +--- a/data/conf/postfix/main.cf ++++ b/data/conf/postfix/main.cf +@@ -150,7 +150,7 @@ smtp_sasl_auth_enable = yes + smtp_sasl_password_maps = proxy:mysql:/opt/postfix/conf/sql/mysql_sasl_passwd_maps_sender_dependent.cf + smtp_sasl_security_options = + smtp_sasl_mechanism_filter = plain, login +-smtp_tls_policy_maps = proxy:mysql:/opt/postfix/conf/sql/mysql_tls_policy_override_maps.cf socketmap:inet:postfix-tlspol:8642:QUERY ++smtp_tls_policy_maps = proxy:mysql:/opt/postfix/conf/sql/mysql_tls_policy_override_maps.cf socketmap:inet:postfix-tlspol:8642:QUERYwithTLSRPT + smtp_header_checks = pcre:/opt/postfix/conf/anonymize_headers.pcre + mail_name = Postcow + # local_transport map catches local destinations and prevents routing local dests when the next map would route "*" +diff --git a/docker-compose.yml b/docker-compose.yml +index 30a7ba96..b3cb8bef 100644 +--- a/docker-compose.yml ++++ b/docker-compose.yml +@@ -382,7 +382,7 @@ services: + - postfix + + postfix-tlspol-mailcow: +- image: ghcr.io/mailcow/postfix-tlspol:1.8.23 ++ image: ghcr.io/mailcow/postfix-tlspol:1.11.0 + depends_on: + unbound-mailcow: + condition: service_healthy diff --git a/tasks/mailcow__mailcow-dockerized-7334/tests/test.sh b/tasks/mailcow__mailcow-dockerized-7334/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..9e57ee9797434a904f9ccd59c8c9732c28345143 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7334/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace c1d75cf808ab990f777f6cbc58c6bfdcdfc0dc49 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "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-7334/tests/verifier.py b/tasks/mailcow__mailcow-dockerized-7334/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7334/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "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-7342/environment/Dockerfile b/tasks/mailcow__mailcow-dockerized-7342/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..3e32f6e491a60db1c785356a245a4e52b01f66ed --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7342/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git 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 c1d75cf808ab990f777f6cbc58c6bfdcdfc0dc49 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard c1d75cf808ab990f777f6cbc58c6bfdcdfc0dc49 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base c1d75cf808ab990f777f6cbc58c6bfdcdfc0dc49 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -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-7342/instruction.md b/tasks/mailcow__mailcow-dockerized-7342/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8c96a6f748ae75090baa8592c0743ff53a898746 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7342/instruction.md @@ -0,0 +1,46 @@ +# Issue + +**Title:** [Web] Add show/hide password toggle on login pages + +## 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 a show/hide password toggle button (eye icon) to the password field on all three login pages: user, admin, and domain admin. + +Clicking the button toggles the field between `type="password"` and `type="text"` and switches between `bi-eye` and `bi-eye-slash` icons accordingly. + +The button uses Bootstrap's `input-group-text` class so its border and styling are consistent with the lock icon on the left side of the input group. + + + +### Affected Containers + +- nginx (web UI templates only — no backend changes) + +## Did you run tests? + +### What did you tested? + +Tested all three login pages (user, admin, domain admin) using a standalone HTML preview with Bootstrap 5 and Bootstrap Icons. + +### What were the final results? (Awaited, got) + +- Awaited: eye icon appears at the right of the password field; clicking it reveals the password and switches to eye-slash icon; clicking again hides it. +- Got: behaviour matches expectation on all three login pages. Button border is visually consistent with the rest of the input group. + +CleanShot 2026-03-21 at 16 03 28 + + +> The original pull request is +> I didn't want this feature to be forgotten. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `c1d75cf808ab`. Edit files in place; the verifier captures your changes via `git diff` 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-7342/solution/patch.diff b/tasks/mailcow__mailcow-dockerized-7342/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..2a910a9f6dfb6e675e848ffca98b6de9679544d1 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7342/solution/patch.diff @@ -0,0 +1,36 @@ +diff --git a/data/web/templates/admin_index.twig b/data/web/templates/admin_index.twig +index 0dcb9145..44b3564c 100644 +--- a/data/web/templates/admin_index.twig ++++ b/data/web/templates/admin_index.twig +@@ -49,6 +49,7 @@ +
+
+ ++ +
+
+
+diff --git a/data/web/templates/domainadmin_index.twig b/data/web/templates/domainadmin_index.twig +index 2fc7bad9..af667756 100644 +--- a/data/web/templates/domainadmin_index.twig ++++ b/data/web/templates/domainadmin_index.twig +@@ -49,6 +49,7 @@ +
+
+ ++ +
+
+
+diff --git a/data/web/templates/user_index.twig b/data/web/templates/user_index.twig +index 28eb6389..a06cdb3f 100644 +--- a/data/web/templates/user_index.twig ++++ b/data/web/templates/user_index.twig +@@ -56,6 +56,7 @@ +
+
+ ++ +
+
+
diff --git a/tasks/mailcow__mailcow-dockerized-7342/solution/solve.sh b/tasks/mailcow__mailcow-dockerized-7342/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7342/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo 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-7342/task.toml b/tasks/mailcow__mailcow-dockerized-7342/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..1a64ca6097afd40367867b13a1d0ccb29b936308 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7342/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/mailcow__mailcow-dockerized-7342" +description = "[Web] Add show/hide password toggle on login pages" + +[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 = "c1d75cf808ab990f777f6cbc58c6bfdcdfc0dc49" +reference = "https://github.com/mailcow/mailcow-dockerized/pull/7342" +source_access = "auto" +built_at = "2026-11-16T16:09:53.143532+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:965d88d851b6ec97adce7b38e2875c610278b92e7811eaa8ae5a4f8252fe6a41" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-08-18T12:25:23Z" +diff_format = "unified" +context_files = [ + "data/web/templates/admin_index.twig", + "data/web/templates/domainadmin_index.twig", + "data/web/templates/user_index.twig", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 3 +difficulty = "trivial" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.463085+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:1e9baf8599607c95669a26dabf592c84a746340e2ff8d795c6bee4261a69eeb8" +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-7342/tests/capture.py b/tasks/mailcow__mailcow-dockerized-7342/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7342/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture 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-7342/tests/instruction.md b/tasks/mailcow__mailcow-dockerized-7342/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8c96a6f748ae75090baa8592c0743ff53a898746 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7342/tests/instruction.md @@ -0,0 +1,46 @@ +# Issue + +**Title:** [Web] Add show/hide password toggle on login pages + +## 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 a show/hide password toggle button (eye icon) to the password field on all three login pages: user, admin, and domain admin. + +Clicking the button toggles the field between `type="password"` and `type="text"` and switches between `bi-eye` and `bi-eye-slash` icons accordingly. + +The button uses Bootstrap's `input-group-text` class so its border and styling are consistent with the lock icon on the left side of the input group. + + + +### Affected Containers + +- nginx (web UI templates only — no backend changes) + +## Did you run tests? + +### What did you tested? + +Tested all three login pages (user, admin, domain admin) using a standalone HTML preview with Bootstrap 5 and Bootstrap Icons. + +### What were the final results? (Awaited, got) + +- Awaited: eye icon appears at the right of the password field; clicking it reveals the password and switches to eye-slash icon; clicking again hides it. +- Got: behaviour matches expectation on all three login pages. Button border is visually consistent with the rest of the input group. + +CleanShot 2026-03-21 at 16 03 28 + + +> The original pull request is +> I didn't want this feature to be forgotten. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `c1d75cf808ab`. Edit files in place; the verifier captures your changes via `git diff` 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-7342/tests/oracle.patch b/tasks/mailcow__mailcow-dockerized-7342/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..2a910a9f6dfb6e675e848ffca98b6de9679544d1 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7342/tests/oracle.patch @@ -0,0 +1,36 @@ +diff --git a/data/web/templates/admin_index.twig b/data/web/templates/admin_index.twig +index 0dcb9145..44b3564c 100644 +--- a/data/web/templates/admin_index.twig ++++ b/data/web/templates/admin_index.twig +@@ -49,6 +49,7 @@ +
+
+ ++ +
+
+
+diff --git a/data/web/templates/domainadmin_index.twig b/data/web/templates/domainadmin_index.twig +index 2fc7bad9..af667756 100644 +--- a/data/web/templates/domainadmin_index.twig ++++ b/data/web/templates/domainadmin_index.twig +@@ -49,6 +49,7 @@ +
+
+ ++ +
+
+
+diff --git a/data/web/templates/user_index.twig b/data/web/templates/user_index.twig +index 28eb6389..a06cdb3f 100644 +--- a/data/web/templates/user_index.twig ++++ b/data/web/templates/user_index.twig +@@ -56,6 +56,7 @@ +
+
+ ++ +
+
+
diff --git a/tasks/mailcow__mailcow-dockerized-7342/tests/test.sh b/tasks/mailcow__mailcow-dockerized-7342/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..9e57ee9797434a904f9ccd59c8c9732c28345143 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7342/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace c1d75cf808ab990f777f6cbc58c6bfdcdfc0dc49 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "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-7342/tests/verifier.py b/tasks/mailcow__mailcow-dockerized-7342/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7342/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "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-7344/environment/Dockerfile b/tasks/mailcow__mailcow-dockerized-7344/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..3e32f6e491a60db1c785356a245a4e52b01f66ed --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7344/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git 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 c1d75cf808ab990f777f6cbc58c6bfdcdfc0dc49 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard c1d75cf808ab990f777f6cbc58c6bfdcdfc0dc49 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base c1d75cf808ab990f777f6cbc58c6bfdcdfc0dc49 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -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-7344/instruction.md b/tasks/mailcow__mailcow-dockerized-7344/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..326bcd8a6b312dca7671834eb5d81503d6f17adb --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7344/instruction.md @@ -0,0 +1,62 @@ +# Issue + +**Title:** [Web] translate password errors in the forced password change modal + +## Description + +## What + +When a user is forced to change their password at next login and enters one that +fails the complexity policy, the modal shows the literal string +`password_complexity` instead of a message. + +## Why + +The forced password change modal is the only password form that posts to the JSON +API (`/api/v1/edit/self`, or `/api/v1/edit/admin` for admins) and renders +`data[0].msg` straight into the alert. The API intentionally returns raw language +keys — every other password form goes through `alertbox_log_parser()`, which +resolves the key against `$lang`. This modal never did. + +## Fix + +Resolve the key against `lang_danger`, which `base.twig` already exposes for +exactly this purpose (it is `json_encode($lang['danger'])`, see +`footer.inc.php:74`, and is used the same way in `admin.js`). No new machinery, no +API change — the API keeps returning stable keys for external consumers, since the +bug is in the presentation layer. + +This also fixes `password_mismatch`, `password_empty` and `access_denied` in the +same modal, and covers the admin path through the same handler. + +The lookup is guarded with `hasOwnProperty`: `msg` is dynamic, and a bare +`lang_danger[msg]` would resolve inherited `Object.prototype` members like +`constructor` to a *function*, which jQuery's `.text()` treats as a callback and +invokes. + +**No language files are touched.** `prerequisites.inc.php:269` loads +`lang.en-gb.json` as the base and merges the active locale over it, so the four +locales that currently lack `danger.password_complexity` (az, gr, lt, nb) inherit +the English string rather than falling back to the raw key. + +## Verification + +- `base.twig` parses clean under Twig (with mailcow's custom `query_string` / + `is_uri` / `rot13` / `formatBytes` extensions registered), before and after. +- Exercised the lookup against the real `danger` section of `lang.en-gb.json`: + +| API returns | before | after | +|---|---|---| +| `password_complexity` | `password_complexity` | Password does not meet the policy | +| `password_mismatch` | `password_mismatch` | Confirmation password does not match | +| `password_empty` | `password_empty` | Password must not be empty | +| `access_denied` | `access_denied` | Access denied or invalid form data | +| unknown key | unchanged | unchanged | +| `'Password change failed.'` (JS fallback) | unchanged | unchanged | +| array form (vsprintf) | unchanged | unchanged | + +- Confirmed all 33 locale files resolve to a real string via the en-gb base merge. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `c1d75cf808ab`. Edit files in place; the verifier captures your changes via `git diff` 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-7344/solution/patch.diff b/tasks/mailcow__mailcow-dockerized-7344/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..be1f9f42f9846a8e2ac61438145ea3e937f6586a --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7344/solution/patch.diff @@ -0,0 +1,15 @@ +diff --git a/data/web/templates/base.twig b/data/web/templates/base.twig +index 9e20b08a..e0f3b5b3 100644 +--- a/data/web/templates/base.twig ++++ b/data/web/templates/base.twig +@@ -473,6 +473,10 @@ function recursiveBase64StrToArrayBuffer(obj) { + window.location.reload(); + } else { + var msg = (data && data[0] && data[0].msg) ? data[0].msg : 'Password change failed.'; ++ // the API returns raw language keys, resolve them like the alert box does ++ if (Object.prototype.hasOwnProperty.call(lang_danger, msg)) { ++ msg = lang_danger[msg]; ++ } + $('#changePWAlert').show().text(msg); + } + }, diff --git a/tasks/mailcow__mailcow-dockerized-7344/solution/solve.sh b/tasks/mailcow__mailcow-dockerized-7344/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7344/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo 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-7344/task.toml b/tasks/mailcow__mailcow-dockerized-7344/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..328705b024ad3294b99a3dc84cff05f6aad925a0 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7344/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/mailcow__mailcow-dockerized-7344" +description = "[Web] translate password errors in the forced password change modal" + +[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 = "c1d75cf808ab990f777f6cbc58c6bfdcdfc0dc49" +reference = "https://github.com/mailcow/mailcow-dockerized/pull/7344" +source_access = "auto" +built_at = "2026-11-16T16:09:53.149804+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:8847f35185ddee0b3290ec1559f258c59bd10dc498f62ddaaaac6b156f333a37" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-08-18T11:31:35Z" +diff_format = "unified" +context_files = [ + "data/web/templates/base.twig", +] +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.463583+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:1e9baf8599607c95669a26dabf592c84a746340e2ff8d795c6bee4261a69eeb8" +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-7344/tests/capture.py b/tasks/mailcow__mailcow-dockerized-7344/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7344/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture 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-7344/tests/instruction.md b/tasks/mailcow__mailcow-dockerized-7344/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..326bcd8a6b312dca7671834eb5d81503d6f17adb --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7344/tests/instruction.md @@ -0,0 +1,62 @@ +# Issue + +**Title:** [Web] translate password errors in the forced password change modal + +## Description + +## What + +When a user is forced to change their password at next login and enters one that +fails the complexity policy, the modal shows the literal string +`password_complexity` instead of a message. + +## Why + +The forced password change modal is the only password form that posts to the JSON +API (`/api/v1/edit/self`, or `/api/v1/edit/admin` for admins) and renders +`data[0].msg` straight into the alert. The API intentionally returns raw language +keys — every other password form goes through `alertbox_log_parser()`, which +resolves the key against `$lang`. This modal never did. + +## Fix + +Resolve the key against `lang_danger`, which `base.twig` already exposes for +exactly this purpose (it is `json_encode($lang['danger'])`, see +`footer.inc.php:74`, and is used the same way in `admin.js`). No new machinery, no +API change — the API keeps returning stable keys for external consumers, since the +bug is in the presentation layer. + +This also fixes `password_mismatch`, `password_empty` and `access_denied` in the +same modal, and covers the admin path through the same handler. + +The lookup is guarded with `hasOwnProperty`: `msg` is dynamic, and a bare +`lang_danger[msg]` would resolve inherited `Object.prototype` members like +`constructor` to a *function*, which jQuery's `.text()` treats as a callback and +invokes. + +**No language files are touched.** `prerequisites.inc.php:269` loads +`lang.en-gb.json` as the base and merges the active locale over it, so the four +locales that currently lack `danger.password_complexity` (az, gr, lt, nb) inherit +the English string rather than falling back to the raw key. + +## Verification + +- `base.twig` parses clean under Twig (with mailcow's custom `query_string` / + `is_uri` / `rot13` / `formatBytes` extensions registered), before and after. +- Exercised the lookup against the real `danger` section of `lang.en-gb.json`: + +| API returns | before | after | +|---|---|---| +| `password_complexity` | `password_complexity` | Password does not meet the policy | +| `password_mismatch` | `password_mismatch` | Confirmation password does not match | +| `password_empty` | `password_empty` | Password must not be empty | +| `access_denied` | `access_denied` | Access denied or invalid form data | +| unknown key | unchanged | unchanged | +| `'Password change failed.'` (JS fallback) | unchanged | unchanged | +| array form (vsprintf) | unchanged | unchanged | + +- Confirmed all 33 locale files resolve to a real string via the en-gb base merge. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `c1d75cf808ab`. Edit files in place; the verifier captures your changes via `git diff` 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-7344/tests/oracle.patch b/tasks/mailcow__mailcow-dockerized-7344/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..be1f9f42f9846a8e2ac61438145ea3e937f6586a --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7344/tests/oracle.patch @@ -0,0 +1,15 @@ +diff --git a/data/web/templates/base.twig b/data/web/templates/base.twig +index 9e20b08a..e0f3b5b3 100644 +--- a/data/web/templates/base.twig ++++ b/data/web/templates/base.twig +@@ -473,6 +473,10 @@ function recursiveBase64StrToArrayBuffer(obj) { + window.location.reload(); + } else { + var msg = (data && data[0] && data[0].msg) ? data[0].msg : 'Password change failed.'; ++ // the API returns raw language keys, resolve them like the alert box does ++ if (Object.prototype.hasOwnProperty.call(lang_danger, msg)) { ++ msg = lang_danger[msg]; ++ } + $('#changePWAlert').show().text(msg); + } + }, diff --git a/tasks/mailcow__mailcow-dockerized-7344/tests/test.sh b/tasks/mailcow__mailcow-dockerized-7344/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..9e57ee9797434a904f9ccd59c8c9732c28345143 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7344/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace c1d75cf808ab990f777f6cbc58c6bfdcdfc0dc49 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "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-7344/tests/verifier.py b/tasks/mailcow__mailcow-dockerized-7344/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7344/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "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-7345/environment/Dockerfile b/tasks/mailcow__mailcow-dockerized-7345/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..3e32f6e491a60db1c785356a245a4e52b01f66ed --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7345/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git 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 c1d75cf808ab990f777f6cbc58c6bfdcdfc0dc49 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard c1d75cf808ab990f777f6cbc58c6bfdcdfc0dc49 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base c1d75cf808ab990f777f6cbc58c6bfdcdfc0dc49 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -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-7345/instruction.md b/tasks/mailcow__mailcow-dockerized-7345/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..41dce315eeb419384d64a1c7aa058da1f8764fe6 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7345/instruction.md @@ -0,0 +1,77 @@ +# Issue + +**Title:** [Web] fix add/time_limited_alias silently discarding requests and validity + +## Description + +## What + +Three defects in `POST /api/v1/add/time_limited_alias`. + +### 1. A request without `description` is silently discarded (the reported bug) + +`description` was read as `$_data['description']` with no guard. When a client omits +it, `null` is bound to `spamalias.description`, which is `TEXT NOT NULL`, so the +insert raises a `PDOException`. + +`set_exception_handler()` is **terminal** — PHP tears down the script once the +handler returns — so `process_add_return()` never runs and nothing is ever echoed. +The client gets `HTTP 200` with an empty body, and no alias exists. Defaulting the +field to an empty string removes the null insert. + +`spamalias.description` is the only `NOT NULL` description column in the schema, +which is why the same unguarded read in `add/domain` and `add/resource` doesn't +fail — both of those columns are nullable. + +### 2. `validity` never worked + +```php +if (isset($_data["validity"]) && !filter_var($_data["validity"], ...)) { error } +else { $_data["validity"] = 8760; } +``` + +When `validity` is present **and valid**, `!filter_var(...)` is `false`, so the +condition is false and the `else` fires — overwriting the user's value with the +default. Only invalid values were rejected; every valid one was discarded: + +| input | before | after | +|---|---|---| +| `24` | 8760 | **24** | +| `1` | 8760 | **1** | +| `87600` | 8760 | **87600** | +| `0` / `87601` / `-5` / `"abc"` | error | error | +| omitted | 8760 | 8760 | + +Nesting the range check fixes it. I'd have had to leave `validity` out of the spec +otherwise — documenting a parameter that provably does nothing seemed worse than +leaving it undocumented. + +### 3. Spec gap + +The spec documented only `username` and `domain`, while the code reads +`description`, `validity` and `permanent` too, so spec-driven clients (Swagger UI, +`python-mailcow`, generated SDKs) could not construct a working request. All three +are now documented. + +## Verification + +- `php -l` clean; `openapi.yaml` parses and exposes all five properties. +- Reproduced the root cause against a real MariaDB using the `spamalias` DDL and the + `sql_mode` from the issue: + - `description = NULL` → `ERROR 1048 (23000): Column 'description' cannot be null` + - `description = ''` → insert succeeds, row created +- Exercised the validity branch across the table above, including boundaries. + +## Not addressed + +The generic error handling. A DB error is still swallowed into an empty `HTTP 200` +for every endpoint, which is the second defect in the issue. Fixing it properly is +more than a bugfix: the handler builds `array('mysql_error', $e)` from the raw +`PDOException`, which carries the SQL statement and schema details, so echoing it to +API clients would turn a silent failure into an information disclosure. That needs +sanitising plus a decision on the status-code contract — a maintainer call, so I've +left the issue open rather than closing it. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `c1d75cf808ab`. Edit files in place; the verifier captures your changes via `git diff` 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-7345/solution/patch.diff b/tasks/mailcow__mailcow-dockerized-7345/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..5ea7e01edc4d78228e0aa84245aea2735d43a2bc --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7345/solution/patch.diff @@ -0,0 +1,67 @@ +diff --git a/data/web/api/openapi.yaml b/data/web/api/openapi.yaml +index 77c58b60..ee154c4d 100644 +--- a/data/web/api/openapi.yaml ++++ b/data/web/api/openapi.yaml +@@ -185,6 +185,9 @@ paths: + example: + username: info@domain.tld + domain: domain.tld ++ description: my time limited alias ++ validity: 8760 ++ permanent: false + properties: + username: + description: 'the mailbox an alias should be created for' +@@ -192,6 +195,15 @@ paths: + domain: + description: "the domain" + type: string ++ description: ++ description: "a description for the alias, defaults to an empty string" ++ type: string ++ validity: ++ description: "how many hours the alias stays valid, 1 to 87600, defaults to 8760 (one year)" ++ type: integer ++ permanent: ++ description: "keep the alias after it expired, defaults to false" ++ type: boolean + type: object + summary: Create time limited alias + /api/v1/add/app-passwd: +diff --git a/data/web/inc/functions.mailbox.inc.php b/data/web/inc/functions.mailbox.inc.php +index a9f17705..3a002864 100644 +--- a/data/web/inc/functions.mailbox.inc.php ++++ b/data/web/inc/functions.mailbox.inc.php +@@ -41,13 +41,15 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { + else { + $username = $_SESSION['mailcow_cc_username']; + } +- if (isset($_data["validity"]) && !filter_var($_data["validity"], FILTER_VALIDATE_INT, array('options' => array('min_range' => 1, 'max_range' => 87600)))) { +- $_SESSION['return'][] = array( +- 'type' => 'danger', +- 'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr), +- 'msg' => 'validity_missing' +- ); +- return false; ++ if (isset($_data["validity"])) { ++ if (!filter_var($_data["validity"], FILTER_VALIDATE_INT, array('options' => array('min_range' => 1, 'max_range' => 87600)))) { ++ $_SESSION['return'][] = array( ++ 'type' => 'danger', ++ 'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr), ++ 'msg' => 'validity_missing' ++ ); ++ return false; ++ } + } + else { + // Default to 1 yr +@@ -60,7 +62,8 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { + $permanent = 0; + } + $domain = $_data['domain']; +- $description = $_data['description']; ++ // spamalias.description is NOT NULL, an absent description must not become a null insert ++ $description = $_data['description'] ?? ''; + $valid_domains[] = mailbox('get', 'mailbox_details', $username)['domain']; + $valid_alias_domains = user_get_alias_details($username)['alias_domains']; + if (!empty($valid_alias_domains)) { diff --git a/tasks/mailcow__mailcow-dockerized-7345/solution/solve.sh b/tasks/mailcow__mailcow-dockerized-7345/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7345/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo 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-7345/task.toml b/tasks/mailcow__mailcow-dockerized-7345/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..c264fe219e3bfd57e2a3f847d3021ac89cc2f004 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7345/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/mailcow__mailcow-dockerized-7345" +description = "[Web] fix add/time_limited_alias silently discarding requests and validity" + +[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 = "c1d75cf808ab990f777f6cbc58c6bfdcdfc0dc49" +reference = "https://github.com/mailcow/mailcow-dockerized/pull/7345" +source_access = "auto" +built_at = "2026-11-16T16:09:53.173947+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:4122353718bfeae833527ca535363d662d043ec6a5e1f35d88bee6310bae8ca4" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-07-28T11:49:37Z" +diff_format = "unified" +context_files = [ + "data/web/api/openapi.yaml", + "data/web/inc/functions.mailbox.inc.php", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 31 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.464084+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:1e9baf8599607c95669a26dabf592c84a746340e2ff8d795c6bee4261a69eeb8" +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-7345/tests/capture.py b/tasks/mailcow__mailcow-dockerized-7345/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7345/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture 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-7345/tests/instruction.md b/tasks/mailcow__mailcow-dockerized-7345/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..41dce315eeb419384d64a1c7aa058da1f8764fe6 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7345/tests/instruction.md @@ -0,0 +1,77 @@ +# Issue + +**Title:** [Web] fix add/time_limited_alias silently discarding requests and validity + +## Description + +## What + +Three defects in `POST /api/v1/add/time_limited_alias`. + +### 1. A request without `description` is silently discarded (the reported bug) + +`description` was read as `$_data['description']` with no guard. When a client omits +it, `null` is bound to `spamalias.description`, which is `TEXT NOT NULL`, so the +insert raises a `PDOException`. + +`set_exception_handler()` is **terminal** — PHP tears down the script once the +handler returns — so `process_add_return()` never runs and nothing is ever echoed. +The client gets `HTTP 200` with an empty body, and no alias exists. Defaulting the +field to an empty string removes the null insert. + +`spamalias.description` is the only `NOT NULL` description column in the schema, +which is why the same unguarded read in `add/domain` and `add/resource` doesn't +fail — both of those columns are nullable. + +### 2. `validity` never worked + +```php +if (isset($_data["validity"]) && !filter_var($_data["validity"], ...)) { error } +else { $_data["validity"] = 8760; } +``` + +When `validity` is present **and valid**, `!filter_var(...)` is `false`, so the +condition is false and the `else` fires — overwriting the user's value with the +default. Only invalid values were rejected; every valid one was discarded: + +| input | before | after | +|---|---|---| +| `24` | 8760 | **24** | +| `1` | 8760 | **1** | +| `87600` | 8760 | **87600** | +| `0` / `87601` / `-5` / `"abc"` | error | error | +| omitted | 8760 | 8760 | + +Nesting the range check fixes it. I'd have had to leave `validity` out of the spec +otherwise — documenting a parameter that provably does nothing seemed worse than +leaving it undocumented. + +### 3. Spec gap + +The spec documented only `username` and `domain`, while the code reads +`description`, `validity` and `permanent` too, so spec-driven clients (Swagger UI, +`python-mailcow`, generated SDKs) could not construct a working request. All three +are now documented. + +## Verification + +- `php -l` clean; `openapi.yaml` parses and exposes all five properties. +- Reproduced the root cause against a real MariaDB using the `spamalias` DDL and the + `sql_mode` from the issue: + - `description = NULL` → `ERROR 1048 (23000): Column 'description' cannot be null` + - `description = ''` → insert succeeds, row created +- Exercised the validity branch across the table above, including boundaries. + +## Not addressed + +The generic error handling. A DB error is still swallowed into an empty `HTTP 200` +for every endpoint, which is the second defect in the issue. Fixing it properly is +more than a bugfix: the handler builds `array('mysql_error', $e)` from the raw +`PDOException`, which carries the SQL statement and schema details, so echoing it to +API clients would turn a silent failure into an information disclosure. That needs +sanitising plus a decision on the status-code contract — a maintainer call, so I've +left the issue open rather than closing it. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `c1d75cf808ab`. Edit files in place; the verifier captures your changes via `git diff` 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-7345/tests/oracle.patch b/tasks/mailcow__mailcow-dockerized-7345/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..5ea7e01edc4d78228e0aa84245aea2735d43a2bc --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7345/tests/oracle.patch @@ -0,0 +1,67 @@ +diff --git a/data/web/api/openapi.yaml b/data/web/api/openapi.yaml +index 77c58b60..ee154c4d 100644 +--- a/data/web/api/openapi.yaml ++++ b/data/web/api/openapi.yaml +@@ -185,6 +185,9 @@ paths: + example: + username: info@domain.tld + domain: domain.tld ++ description: my time limited alias ++ validity: 8760 ++ permanent: false + properties: + username: + description: 'the mailbox an alias should be created for' +@@ -192,6 +195,15 @@ paths: + domain: + description: "the domain" + type: string ++ description: ++ description: "a description for the alias, defaults to an empty string" ++ type: string ++ validity: ++ description: "how many hours the alias stays valid, 1 to 87600, defaults to 8760 (one year)" ++ type: integer ++ permanent: ++ description: "keep the alias after it expired, defaults to false" ++ type: boolean + type: object + summary: Create time limited alias + /api/v1/add/app-passwd: +diff --git a/data/web/inc/functions.mailbox.inc.php b/data/web/inc/functions.mailbox.inc.php +index a9f17705..3a002864 100644 +--- a/data/web/inc/functions.mailbox.inc.php ++++ b/data/web/inc/functions.mailbox.inc.php +@@ -41,13 +41,15 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { + else { + $username = $_SESSION['mailcow_cc_username']; + } +- if (isset($_data["validity"]) && !filter_var($_data["validity"], FILTER_VALIDATE_INT, array('options' => array('min_range' => 1, 'max_range' => 87600)))) { +- $_SESSION['return'][] = array( +- 'type' => 'danger', +- 'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr), +- 'msg' => 'validity_missing' +- ); +- return false; ++ if (isset($_data["validity"])) { ++ if (!filter_var($_data["validity"], FILTER_VALIDATE_INT, array('options' => array('min_range' => 1, 'max_range' => 87600)))) { ++ $_SESSION['return'][] = array( ++ 'type' => 'danger', ++ 'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr), ++ 'msg' => 'validity_missing' ++ ); ++ return false; ++ } + } + else { + // Default to 1 yr +@@ -60,7 +62,8 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { + $permanent = 0; + } + $domain = $_data['domain']; +- $description = $_data['description']; ++ // spamalias.description is NOT NULL, an absent description must not become a null insert ++ $description = $_data['description'] ?? ''; + $valid_domains[] = mailbox('get', 'mailbox_details', $username)['domain']; + $valid_alias_domains = user_get_alias_details($username)['alias_domains']; + if (!empty($valid_alias_domains)) { diff --git a/tasks/mailcow__mailcow-dockerized-7345/tests/test.sh b/tasks/mailcow__mailcow-dockerized-7345/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..9e57ee9797434a904f9ccd59c8c9732c28345143 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7345/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace c1d75cf808ab990f777f6cbc58c6bfdcdfc0dc49 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "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-7345/tests/verifier.py b/tasks/mailcow__mailcow-dockerized-7345/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7345/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "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-7347/environment/Dockerfile b/tasks/mailcow__mailcow-dockerized-7347/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..3e32f6e491a60db1c785356a245a4e52b01f66ed --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7347/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git 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 c1d75cf808ab990f777f6cbc58c6bfdcdfc0dc49 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard c1d75cf808ab990f777f6cbc58c6bfdcdfc0dc49 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base c1d75cf808ab990f777f6cbc58c6bfdcdfc0dc49 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -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-7347/instruction.md b/tasks/mailcow__mailcow-dockerized-7347/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c8ec12778423ccaf4f120ecd1e8615f2de3e0275 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7347/instruction.md @@ -0,0 +1,70 @@ +# Issue + +**Title:** [Web] use absolute RHS names in generated DNS zonefile + +## Description + +## What + +The DNS overview page's **Download** button produces a `$ORIGIN` zonefile, but the +right-hand side of `MX`, `CNAME` and `SRV` records was written as a **relative** +name. A target like `mail.example.net` is then interpreted relative to the origin +and expands to `mail.example.net.example.org.` — invalid, exactly as reported. + +The only prior attempt at absolutizing was: + +```php +$dns_data .= str_replace($domain, $domain . '.', $val); +``` + +which appended a dot only to targets that happened to contain the *origin* domain — +so any cross-domain target (the common case: mail host on a different domain than +the mail domain) stayed relative. That same `str_replace` also **corrupted TXT +values** containing the origin, e.g. a DMARC `rua=mailto:x@example.org` became +`...@example.org.`. + +## Fix + +Absolutize the RHS **per record type, at export time only**: +- `MX` / `CNAME` target, and the `SRV` target token → trailing dot +- ports, the SRV root target `.`, IP literals and `TXT` character strings → left as-is + +The `$records` array used for the **on-page live DNS validation** is untouched, so +the comparison against `dns_get_record()` output (which returns bare names) still +works. The change is purely in the downloadable zonefile generation. + +## Verification + +Ran the real endpoint on a live mailcow stack (domain on a different domain than the +mail host, so targets are cross-domain — the reporter's scenario), before and after, +reading the actual base64 zonefile the Download button serves: + +**Before** +``` +@ IN MX mail.local.test +autodiscover IN CNAME mail.local.test +_autodiscover._tcp IN SRV mail.local.test 8090 +_pop3._tcp IN SRV . 0 +``` +**After** +``` +@ IN MX mail.local.test. +autodiscover IN CNAME mail.local.test. +_autodiscover._tcp IN SRV mail.local.test. 8090 +_pop3._tcp IN SRV . 0 +``` + +- Every hostname RHS is now absolute; SRV ports preserved; SRV root `.` untouched; + `TXT`/DKIM values left literal. +- The on-page validation table still renders (HTTP 200, no PHP error). +- `php -l` clean. + +## Scope + +Limited to trailing dots, as the issue requests. I intentionally did **not** change +the non-standard `MX`/`SRV` RDATA shape (missing MX preference, SRV `target port` +ordering) — that's a separate concern and would alter the on-screen table too. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `c1d75cf808ab`. Edit files in place; the verifier captures your changes via `git diff` 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-7347/solution/patch.diff b/tasks/mailcow__mailcow-dockerized-7347/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..0d314d03d2e6320fe26d23efaca8a151c25f7eaa --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7347/solution/patch.diff @@ -0,0 +1,49 @@ +diff --git a/data/web/inc/ajax/dns_diagnostics.php b/data/web/inc/ajax/dns_diagnostics.php +index 95e34e88..1987a88c 100644 +--- a/data/web/inc/ajax/dns_diagnostics.php ++++ b/data/web/inc/ajax/dns_diagnostics.php +@@ -442,6 +442,16 @@ if (isset($_SESSION['mailcow_cc_role']) && ($_SESSION['mailcow_cc_role'] == "adm + + unset($record); + ++ // Make a hostname RHS absolute so it is not read relative to $ORIGIN. ++ // Already-absolute names, the SRV root target "." and IP addresses are left alone. ++ $absolutize = function($host) { ++ $host = trim($host); ++ if ($host === '' || $host === '.' || substr($host, -1) === '.' || filter_var($host, FILTER_VALIDATE_IP)) { ++ return $host; ++ } ++ return $host . '.'; ++ }; ++ + $dns_data = sprintf("\$ORIGIN %s.\n", $domain); + foreach ($records as $record) { + if ($domain == substr($record[0], -strlen($domain))) { +@@ -462,16 +472,26 @@ if (isset($_SESSION['mailcow_cc_role']) && ($_SESSION['mailcow_cc_role'] == "adm + $val = str_replace(state_optional, '', $val); + $val = str_replace(state_good, '', $val); + if (strlen($val) > 0) { ++ // these are all TXT values, their RHS is a character string, not a name + $vals[] = sprintf("%s\tIN\t%s\t%s\n", $label, $record[1], $val); + } + } + } + else { ++ if ($record[1] == 'MX' || $record[1] == 'CNAME') { ++ $val = $absolutize($val); ++ } ++ elseif ($record[1] == 'SRV') { ++ // format here is "target port"; only the target is a name ++ $parts = explode(' ', $val, 2); ++ $parts[0] = $absolutize($parts[0]); ++ $val = implode(' ', $parts); ++ } + $vals[] = sprintf("%s\tIN\t%s\t%s\n", $label, $record[1], $val); + } + + foreach ($vals as $val) { +- $dns_data .= str_replace($domain, $domain . '.', $val); ++ $dns_data .= $val; + } + } + } diff --git a/tasks/mailcow__mailcow-dockerized-7347/solution/solve.sh b/tasks/mailcow__mailcow-dockerized-7347/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7347/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo 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-7347/task.toml b/tasks/mailcow__mailcow-dockerized-7347/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..390aa78f98bbbe557472722044af6be3a835c4cc --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7347/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/mailcow__mailcow-dockerized-7347" +description = "[Web] use absolute RHS names in generated DNS zonefile" + +[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 = "c1d75cf808ab990f777f6cbc58c6bfdcdfc0dc49" +reference = "https://github.com/mailcow/mailcow-dockerized/pull/7347" +source_access = "auto" +built_at = "2026-11-16T16:09:53.147963+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:7e26a581c198d270481c747c9a4e215ef77f36a4621cee76330d40b693950f4f" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-08-18T12:30:51Z" +diff_format = "unified" +context_files = [ + "data/web/inc/ajax/dns_diagnostics.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.464571+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:1e9baf8599607c95669a26dabf592c84a746340e2ff8d795c6bee4261a69eeb8" +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-7347/tests/capture.py b/tasks/mailcow__mailcow-dockerized-7347/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7347/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture 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-7347/tests/instruction.md b/tasks/mailcow__mailcow-dockerized-7347/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c8ec12778423ccaf4f120ecd1e8615f2de3e0275 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7347/tests/instruction.md @@ -0,0 +1,70 @@ +# Issue + +**Title:** [Web] use absolute RHS names in generated DNS zonefile + +## Description + +## What + +The DNS overview page's **Download** button produces a `$ORIGIN` zonefile, but the +right-hand side of `MX`, `CNAME` and `SRV` records was written as a **relative** +name. A target like `mail.example.net` is then interpreted relative to the origin +and expands to `mail.example.net.example.org.` — invalid, exactly as reported. + +The only prior attempt at absolutizing was: + +```php +$dns_data .= str_replace($domain, $domain . '.', $val); +``` + +which appended a dot only to targets that happened to contain the *origin* domain — +so any cross-domain target (the common case: mail host on a different domain than +the mail domain) stayed relative. That same `str_replace` also **corrupted TXT +values** containing the origin, e.g. a DMARC `rua=mailto:x@example.org` became +`...@example.org.`. + +## Fix + +Absolutize the RHS **per record type, at export time only**: +- `MX` / `CNAME` target, and the `SRV` target token → trailing dot +- ports, the SRV root target `.`, IP literals and `TXT` character strings → left as-is + +The `$records` array used for the **on-page live DNS validation** is untouched, so +the comparison against `dns_get_record()` output (which returns bare names) still +works. The change is purely in the downloadable zonefile generation. + +## Verification + +Ran the real endpoint on a live mailcow stack (domain on a different domain than the +mail host, so targets are cross-domain — the reporter's scenario), before and after, +reading the actual base64 zonefile the Download button serves: + +**Before** +``` +@ IN MX mail.local.test +autodiscover IN CNAME mail.local.test +_autodiscover._tcp IN SRV mail.local.test 8090 +_pop3._tcp IN SRV . 0 +``` +**After** +``` +@ IN MX mail.local.test. +autodiscover IN CNAME mail.local.test. +_autodiscover._tcp IN SRV mail.local.test. 8090 +_pop3._tcp IN SRV . 0 +``` + +- Every hostname RHS is now absolute; SRV ports preserved; SRV root `.` untouched; + `TXT`/DKIM values left literal. +- The on-page validation table still renders (HTTP 200, no PHP error). +- `php -l` clean. + +## Scope + +Limited to trailing dots, as the issue requests. I intentionally did **not** change +the non-standard `MX`/`SRV` RDATA shape (missing MX preference, SRV `target port` +ordering) — that's a separate concern and would alter the on-screen table too. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `c1d75cf808ab`. Edit files in place; the verifier captures your changes via `git diff` 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-7347/tests/oracle.patch b/tasks/mailcow__mailcow-dockerized-7347/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..0d314d03d2e6320fe26d23efaca8a151c25f7eaa --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7347/tests/oracle.patch @@ -0,0 +1,49 @@ +diff --git a/data/web/inc/ajax/dns_diagnostics.php b/data/web/inc/ajax/dns_diagnostics.php +index 95e34e88..1987a88c 100644 +--- a/data/web/inc/ajax/dns_diagnostics.php ++++ b/data/web/inc/ajax/dns_diagnostics.php +@@ -442,6 +442,16 @@ if (isset($_SESSION['mailcow_cc_role']) && ($_SESSION['mailcow_cc_role'] == "adm + + unset($record); + ++ // Make a hostname RHS absolute so it is not read relative to $ORIGIN. ++ // Already-absolute names, the SRV root target "." and IP addresses are left alone. ++ $absolutize = function($host) { ++ $host = trim($host); ++ if ($host === '' || $host === '.' || substr($host, -1) === '.' || filter_var($host, FILTER_VALIDATE_IP)) { ++ return $host; ++ } ++ return $host . '.'; ++ }; ++ + $dns_data = sprintf("\$ORIGIN %s.\n", $domain); + foreach ($records as $record) { + if ($domain == substr($record[0], -strlen($domain))) { +@@ -462,16 +472,26 @@ if (isset($_SESSION['mailcow_cc_role']) && ($_SESSION['mailcow_cc_role'] == "adm + $val = str_replace(state_optional, '', $val); + $val = str_replace(state_good, '', $val); + if (strlen($val) > 0) { ++ // these are all TXT values, their RHS is a character string, not a name + $vals[] = sprintf("%s\tIN\t%s\t%s\n", $label, $record[1], $val); + } + } + } + else { ++ if ($record[1] == 'MX' || $record[1] == 'CNAME') { ++ $val = $absolutize($val); ++ } ++ elseif ($record[1] == 'SRV') { ++ // format here is "target port"; only the target is a name ++ $parts = explode(' ', $val, 2); ++ $parts[0] = $absolutize($parts[0]); ++ $val = implode(' ', $parts); ++ } + $vals[] = sprintf("%s\tIN\t%s\t%s\n", $label, $record[1], $val); + } + + foreach ($vals as $val) { +- $dns_data .= str_replace($domain, $domain . '.', $val); ++ $dns_data .= $val; + } + } + } diff --git a/tasks/mailcow__mailcow-dockerized-7347/tests/test.sh b/tasks/mailcow__mailcow-dockerized-7347/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..9e57ee9797434a904f9ccd59c8c9732c28345143 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7347/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace c1d75cf808ab990f777f6cbc58c6bfdcdfc0dc49 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "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-7347/tests/verifier.py b/tasks/mailcow__mailcow-dockerized-7347/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7347/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "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-7348/environment/Dockerfile b/tasks/mailcow__mailcow-dockerized-7348/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..3e32f6e491a60db1c785356a245a4e52b01f66ed --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7348/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git 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 c1d75cf808ab990f777f6cbc58c6bfdcdfc0dc49 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard c1d75cf808ab990f777f6cbc58c6bfdcdfc0dc49 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base c1d75cf808ab990f777f6cbc58c6bfdcdfc0dc49 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -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-7348/instruction.md b/tasks/mailcow__mailcow-dockerized-7348/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c3286da14f12cf6487078ef440970f80836d4989 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7348/instruction.md @@ -0,0 +1,43 @@ +# Issue + +**Title:** [Web] return sender_acl in get/mailbox API + +## Description + +## What + +`sender_acl` can be **set** via `POST /api/v1/edit/mailbox`, but it was never +**returned** by `GET /api/v1/get/mailbox/{mailbox}` or `.../get/mailbox/all`. An API +client therefore can't read back what it wrote, and can't see a mailbox's send-as +permissions at all. + +## Fix + +Add the mailbox's internal send-as ACL to `mailbox_details` as `sender_acl` — an +array of `send_as` values from the `sender_acl` table (`external = 0`), mirroring the +field `edit/mailbox` accepts, so a get→edit round-trip is symmetric. + +It's added in the same detailed-fields block as `rl`/quota info, so the deliberately +lightweight `get/mailbox/reduced` endpoint is unaffected. + +## Verification (live stack) + +``` +# before setting anything +GET /api/v1/get/mailbox/alicetest@example-test.com + -> sender_acl: [] (key now present, empty) + +# set it +POST /api/v1/edit/mailbox {"attr":{"sender_acl":["*"]},"items":[...]} -> success + +# read back +GET /api/v1/get/mailbox/alicetest@example-test.com -> sender_acl: ["*"] +GET /api/v1/get/mailbox/all -> sender_acl: ["*"] +GET /api/v1/get/mailbox/reduced -> (no sender_acl — stays light) +``` + +Round-trip confirmed; `reduced` unchanged; `php -l` clean. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `c1d75cf808ab`. Edit files in place; the verifier captures your changes via `git diff` 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-7348/solution/patch.diff b/tasks/mailcow__mailcow-dockerized-7348/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..9ecdc00daebda0a6741aa1c5f732e380aa82186c --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7348/solution/patch.diff @@ -0,0 +1,19 @@ +diff --git a/data/web/inc/functions.mailbox.inc.php b/data/web/inc/functions.mailbox.inc.php +index a9f17705..ba2756a4 100644 +--- a/data/web/inc/functions.mailbox.inc.php ++++ b/data/web/inc/functions.mailbox.inc.php +@@ -5320,6 +5320,14 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { + $mailboxdata['rl_scope'] = 'domain'; + } + $mailboxdata['is_relayed'] = $row['backupmx']; ++ // Internal send-as ACL for this mailbox, mirrors the sender_acl field accepted by edit/mailbox ++ $mailboxdata['sender_acl'] = array(); ++ $stmt = $pdo->prepare("SELECT `send_as` FROM `sender_acl` WHERE `logged_in_as` = :username AND `external` = '0'"); ++ $stmt->execute(array(':username' => $_data)); ++ $sender_acl_rows = $stmt->fetchAll(PDO::FETCH_ASSOC); ++ foreach ($sender_acl_rows as $sender_acl_row) { ++ $mailboxdata['sender_acl'][] = $sender_acl_row['send_as']; ++ } + } + $stmt = $pdo->prepare("SELECT `tag_name` + FROM `tags_mailbox` WHERE `username`= :username"); diff --git a/tasks/mailcow__mailcow-dockerized-7348/solution/solve.sh b/tasks/mailcow__mailcow-dockerized-7348/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7348/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo 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-7348/task.toml b/tasks/mailcow__mailcow-dockerized-7348/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..869f5437d25883cf6aa7511c7650340394070526 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7348/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/mailcow__mailcow-dockerized-7348" +description = "[Web] return sender_acl in get/mailbox API" + +[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 = "c1d75cf808ab990f777f6cbc58c6bfdcdfc0dc49" +reference = "https://github.com/mailcow/mailcow-dockerized/pull/7348" +source_access = "auto" +built_at = "2026-11-16T16:09:53.172195+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:8dd33222e902b09639cc4c3066301beb079fd886fdfcac8192b9cb3e73668c1d" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-07-28T12:12:57Z" +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 = 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.465057+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:1e9baf8599607c95669a26dabf592c84a746340e2ff8d795c6bee4261a69eeb8" +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-7348/tests/capture.py b/tasks/mailcow__mailcow-dockerized-7348/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7348/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture 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-7348/tests/instruction.md b/tasks/mailcow__mailcow-dockerized-7348/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c3286da14f12cf6487078ef440970f80836d4989 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7348/tests/instruction.md @@ -0,0 +1,43 @@ +# Issue + +**Title:** [Web] return sender_acl in get/mailbox API + +## Description + +## What + +`sender_acl` can be **set** via `POST /api/v1/edit/mailbox`, but it was never +**returned** by `GET /api/v1/get/mailbox/{mailbox}` or `.../get/mailbox/all`. An API +client therefore can't read back what it wrote, and can't see a mailbox's send-as +permissions at all. + +## Fix + +Add the mailbox's internal send-as ACL to `mailbox_details` as `sender_acl` — an +array of `send_as` values from the `sender_acl` table (`external = 0`), mirroring the +field `edit/mailbox` accepts, so a get→edit round-trip is symmetric. + +It's added in the same detailed-fields block as `rl`/quota info, so the deliberately +lightweight `get/mailbox/reduced` endpoint is unaffected. + +## Verification (live stack) + +``` +# before setting anything +GET /api/v1/get/mailbox/alicetest@example-test.com + -> sender_acl: [] (key now present, empty) + +# set it +POST /api/v1/edit/mailbox {"attr":{"sender_acl":["*"]},"items":[...]} -> success + +# read back +GET /api/v1/get/mailbox/alicetest@example-test.com -> sender_acl: ["*"] +GET /api/v1/get/mailbox/all -> sender_acl: ["*"] +GET /api/v1/get/mailbox/reduced -> (no sender_acl — stays light) +``` + +Round-trip confirmed; `reduced` unchanged; `php -l` clean. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `c1d75cf808ab`. Edit files in place; the verifier captures your changes via `git diff` 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-7348/tests/oracle.patch b/tasks/mailcow__mailcow-dockerized-7348/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..9ecdc00daebda0a6741aa1c5f732e380aa82186c --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7348/tests/oracle.patch @@ -0,0 +1,19 @@ +diff --git a/data/web/inc/functions.mailbox.inc.php b/data/web/inc/functions.mailbox.inc.php +index a9f17705..ba2756a4 100644 +--- a/data/web/inc/functions.mailbox.inc.php ++++ b/data/web/inc/functions.mailbox.inc.php +@@ -5320,6 +5320,14 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { + $mailboxdata['rl_scope'] = 'domain'; + } + $mailboxdata['is_relayed'] = $row['backupmx']; ++ // Internal send-as ACL for this mailbox, mirrors the sender_acl field accepted by edit/mailbox ++ $mailboxdata['sender_acl'] = array(); ++ $stmt = $pdo->prepare("SELECT `send_as` FROM `sender_acl` WHERE `logged_in_as` = :username AND `external` = '0'"); ++ $stmt->execute(array(':username' => $_data)); ++ $sender_acl_rows = $stmt->fetchAll(PDO::FETCH_ASSOC); ++ foreach ($sender_acl_rows as $sender_acl_row) { ++ $mailboxdata['sender_acl'][] = $sender_acl_row['send_as']; ++ } + } + $stmt = $pdo->prepare("SELECT `tag_name` + FROM `tags_mailbox` WHERE `username`= :username"); diff --git a/tasks/mailcow__mailcow-dockerized-7348/tests/test.sh b/tasks/mailcow__mailcow-dockerized-7348/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..9e57ee9797434a904f9ccd59c8c9732c28345143 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7348/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace c1d75cf808ab990f777f6cbc58c6bfdcdfc0dc49 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "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-7348/tests/verifier.py b/tasks/mailcow__mailcow-dockerized-7348/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7348/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "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-7349/environment/Dockerfile b/tasks/mailcow__mailcow-dockerized-7349/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..3e32f6e491a60db1c785356a245a4e52b01f66ed --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7349/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git 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 c1d75cf808ab990f777f6cbc58c6bfdcdfc0dc49 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard c1d75cf808ab990f777f6cbc58c6bfdcdfc0dc49 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base c1d75cf808ab990f777f6cbc58c6bfdcdfc0dc49 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -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-7349/instruction.md b/tasks/mailcow__mailcow-dockerized-7349/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1aeea6b920f764720a2e7dcd3c04d2dc68d99fe3 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7349/instruction.md @@ -0,0 +1,42 @@ +# Issue + +**Title:** [Web] redirect deep links to the matching login page + +## Description + +## What + +An unauthenticated request to a deep link like `/admin/dashboard` redirected to `/` +(the **user** login) instead of the **admin** login. `protect_route()` sent every +unauthenticated visitor to `/` regardless of which area the link belonged to. + +## Fix + +Choose the login page from the request path in the unauthenticated branch of +`protect_route()`: + +- `/admin/*` → `/admin` +- `/domainadmin/*` → `/domainadmin` +- everything else → `/` (unchanged) + +## Verification (live stack, unauthenticated `curl`) + +| deep link | before | after | +|---|---|---| +| `/admin/dashboard` | `/` | `/admin` | +| `/admin/mailbox` | `/` | `/admin` | +| `/domainadmin/mailbox` | `/` | `/domainadmin` | +| `/user` | `/` | `/` (unchanged) | + +`php -l` clean. + +## Scope + +This lands deep links on the correct login page, as the issue asks. It does **not** +implement the reporter's optional "redirect back to the originally requested URL +after login" idea — that's a larger change (persisting and validating a return URL) +and better handled separately. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `c1d75cf808ab`. Edit files in place; the verifier captures your changes via `git diff` 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-7349/solution/patch.diff b/tasks/mailcow__mailcow-dockerized-7349/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..5995eb86b7561a79c8b65c4e55b20e423906baf6 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7349/solution/patch.diff @@ -0,0 +1,22 @@ +diff --git a/data/web/inc/functions.inc.php b/data/web/inc/functions.inc.php +index 89f14b57..a796f158 100644 +--- a/data/web/inc/functions.inc.php ++++ b/data/web/inc/functions.inc.php +@@ -3503,7 +3503,16 @@ function protect_route($allowed_roles = ['admin', 'domainadmin', 'user'], $redir + if (isset($redirects['unauthenticated'])) { + header('Location: ' . $redirects['unauthenticated']); + } else { +- header('Location: /'); ++ // Send a deep link to the login page for its area instead of the user login at /, ++ // e.g. /admin/dashboard -> /admin rather than / ++ $request_uri = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '/'; ++ if (strpos($request_uri, '/admin/') === 0) { ++ header('Location: /admin'); ++ } elseif (strpos($request_uri, '/domainadmin/') === 0) { ++ header('Location: /domainadmin'); ++ } else { ++ header('Location: /'); ++ } + } + exit(); + } diff --git a/tasks/mailcow__mailcow-dockerized-7349/solution/solve.sh b/tasks/mailcow__mailcow-dockerized-7349/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7349/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo 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-7349/task.toml b/tasks/mailcow__mailcow-dockerized-7349/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..6e2bd168b7b1cfef1274487f7bedaf30d482ac55 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7349/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/mailcow__mailcow-dockerized-7349" +description = "[Web] redirect deep links to the matching login page" + +[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 = "c1d75cf808ab990f777f6cbc58c6bfdcdfc0dc49" +reference = "https://github.com/mailcow/mailcow-dockerized/pull/7349" +source_access = "auto" +built_at = "2026-11-16T16:09:53.146333+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:1060d86f095dc2a032b7af75d69a853f88e031f2d6d1378cd0615a2d7b59eca8" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-08-18T12:37:32Z" +diff_format = "unified" +context_files = [ + "data/web/inc/functions.inc.php", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 11 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.465540+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:1e9baf8599607c95669a26dabf592c84a746340e2ff8d795c6bee4261a69eeb8" +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-7349/tests/capture.py b/tasks/mailcow__mailcow-dockerized-7349/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7349/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture 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-7349/tests/instruction.md b/tasks/mailcow__mailcow-dockerized-7349/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1aeea6b920f764720a2e7dcd3c04d2dc68d99fe3 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7349/tests/instruction.md @@ -0,0 +1,42 @@ +# Issue + +**Title:** [Web] redirect deep links to the matching login page + +## Description + +## What + +An unauthenticated request to a deep link like `/admin/dashboard` redirected to `/` +(the **user** login) instead of the **admin** login. `protect_route()` sent every +unauthenticated visitor to `/` regardless of which area the link belonged to. + +## Fix + +Choose the login page from the request path in the unauthenticated branch of +`protect_route()`: + +- `/admin/*` → `/admin` +- `/domainadmin/*` → `/domainadmin` +- everything else → `/` (unchanged) + +## Verification (live stack, unauthenticated `curl`) + +| deep link | before | after | +|---|---|---| +| `/admin/dashboard` | `/` | `/admin` | +| `/admin/mailbox` | `/` | `/admin` | +| `/domainadmin/mailbox` | `/` | `/domainadmin` | +| `/user` | `/` | `/` (unchanged) | + +`php -l` clean. + +## Scope + +This lands deep links on the correct login page, as the issue asks. It does **not** +implement the reporter's optional "redirect back to the originally requested URL +after login" idea — that's a larger change (persisting and validating a return URL) +and better handled separately. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `c1d75cf808ab`. Edit files in place; the verifier captures your changes via `git diff` 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-7349/tests/oracle.patch b/tasks/mailcow__mailcow-dockerized-7349/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..5995eb86b7561a79c8b65c4e55b20e423906baf6 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7349/tests/oracle.patch @@ -0,0 +1,22 @@ +diff --git a/data/web/inc/functions.inc.php b/data/web/inc/functions.inc.php +index 89f14b57..a796f158 100644 +--- a/data/web/inc/functions.inc.php ++++ b/data/web/inc/functions.inc.php +@@ -3503,7 +3503,16 @@ function protect_route($allowed_roles = ['admin', 'domainadmin', 'user'], $redir + if (isset($redirects['unauthenticated'])) { + header('Location: ' . $redirects['unauthenticated']); + } else { +- header('Location: /'); ++ // Send a deep link to the login page for its area instead of the user login at /, ++ // e.g. /admin/dashboard -> /admin rather than / ++ $request_uri = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '/'; ++ if (strpos($request_uri, '/admin/') === 0) { ++ header('Location: /admin'); ++ } elseif (strpos($request_uri, '/domainadmin/') === 0) { ++ header('Location: /domainadmin'); ++ } else { ++ header('Location: /'); ++ } + } + exit(); + } diff --git a/tasks/mailcow__mailcow-dockerized-7349/tests/test.sh b/tasks/mailcow__mailcow-dockerized-7349/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..9e57ee9797434a904f9ccd59c8c9732c28345143 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7349/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace c1d75cf808ab990f777f6cbc58c6bfdcdfc0dc49 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "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-7349/tests/verifier.py b/tasks/mailcow__mailcow-dockerized-7349/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7349/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "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-7358/environment/Dockerfile b/tasks/mailcow__mailcow-dockerized-7358/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..f7d991eff136d4900e40656601019e1351e02495 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7358/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git 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 4b62af9d023d5bda57f85293513631013eccd8df 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4b62af9d023d5bda57f85293513631013eccd8df \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4b62af9d023d5bda57f85293513631013eccd8df \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -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-7358/instruction.md b/tasks/mailcow__mailcow-dockerized-7358/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..df808e91391ec91e829a4a135273a968d1d3fa94 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7358/instruction.md @@ -0,0 +1,37 @@ +# Issue + +**Title:** Fix nginx CVE-2026-42533 + +## 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? + +nginx version bump to 1.30.4 + +### Short Description + +Fix CVE-2026-42533 in nginx image. + +### Affected Containers + +- nginx + +## Did you run tests? + +### What did you tested? + +check if nginx container starts with correct version + +### What were the final results? (Awaited, got) + +awaited nginx version 1.30.4, got version 1.30.4 + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4b62af9d023d`. Edit files in place; the verifier captures your changes via `git diff` 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-7358/solution/patch.diff b/tasks/mailcow__mailcow-dockerized-7358/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..815f4c65742debade84bb8f4c442755a6dbd64c7 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7358/solution/patch.diff @@ -0,0 +1,23 @@ +diff --git a/data/Dockerfiles/nginx/Dockerfile b/data/Dockerfiles/nginx/Dockerfile +index 65b34838..d3280a33 100644 +--- a/data/Dockerfiles/nginx/Dockerfile ++++ b/data/Dockerfiles/nginx/Dockerfile +@@ -1,4 +1,4 @@ +-FROM nginx:1.30.3-alpine ++FROM nginx:1.30.4-alpine + LABEL maintainer "The Infrastructure Company GmbH " + + ENV PIP_BREAK_SYSTEM_PACKAGES=1 +diff --git a/docker-compose.yml b/docker-compose.yml +index 30a7ba96..dab078c8 100644 +--- a/docker-compose.yml ++++ b/docker-compose.yml +@@ -419,7 +419,7 @@ services: + - php-fpm-mailcow + - sogo-mailcow + - rspamd-mailcow +- image: ghcr.io/mailcow/nginx:1.30.3-1 ++ image: ghcr.io/mailcow/nginx:1.30.4 + dns: + - ${IPV4_NETWORK:-172.22.1}.254 + environment: diff --git a/tasks/mailcow__mailcow-dockerized-7358/solution/solve.sh b/tasks/mailcow__mailcow-dockerized-7358/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7358/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo 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-7358/task.toml b/tasks/mailcow__mailcow-dockerized-7358/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..92dd6810ca409f6e06a7854fbcc7bea75bda5b3b --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7358/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/mailcow__mailcow-dockerized-7358" +description = "Fix nginx CVE-2026-42533" + +[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 = "4b62af9d023d5bda57f85293513631013eccd8df" +reference = "https://github.com/mailcow/mailcow-dockerized/pull/7358" +source_access = "auto" +built_at = "2026-11-16T16:09:53.170692+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:c8a98fd660ec3acf2726b50148976d7fe4aebd26e547bc2c181e5bc44984418f" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-07-28T12:40:30Z" +diff_format = "unified" +context_files = [ + "data/Dockerfiles/nginx/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.466019+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:d797316cda26c88c8082952a3fed2131f2fefd046a1d056ca38bb2fd825dc74f" +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-7358/tests/capture.py b/tasks/mailcow__mailcow-dockerized-7358/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7358/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture 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-7358/tests/instruction.md b/tasks/mailcow__mailcow-dockerized-7358/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..df808e91391ec91e829a4a135273a968d1d3fa94 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7358/tests/instruction.md @@ -0,0 +1,37 @@ +# Issue + +**Title:** Fix nginx CVE-2026-42533 + +## 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? + +nginx version bump to 1.30.4 + +### Short Description + +Fix CVE-2026-42533 in nginx image. + +### Affected Containers + +- nginx + +## Did you run tests? + +### What did you tested? + +check if nginx container starts with correct version + +### What were the final results? (Awaited, got) + +awaited nginx version 1.30.4, got version 1.30.4 + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4b62af9d023d`. Edit files in place; the verifier captures your changes via `git diff` 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-7358/tests/oracle.patch b/tasks/mailcow__mailcow-dockerized-7358/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..815f4c65742debade84bb8f4c442755a6dbd64c7 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7358/tests/oracle.patch @@ -0,0 +1,23 @@ +diff --git a/data/Dockerfiles/nginx/Dockerfile b/data/Dockerfiles/nginx/Dockerfile +index 65b34838..d3280a33 100644 +--- a/data/Dockerfiles/nginx/Dockerfile ++++ b/data/Dockerfiles/nginx/Dockerfile +@@ -1,4 +1,4 @@ +-FROM nginx:1.30.3-alpine ++FROM nginx:1.30.4-alpine + LABEL maintainer "The Infrastructure Company GmbH " + + ENV PIP_BREAK_SYSTEM_PACKAGES=1 +diff --git a/docker-compose.yml b/docker-compose.yml +index 30a7ba96..dab078c8 100644 +--- a/docker-compose.yml ++++ b/docker-compose.yml +@@ -419,7 +419,7 @@ services: + - php-fpm-mailcow + - sogo-mailcow + - rspamd-mailcow +- image: ghcr.io/mailcow/nginx:1.30.3-1 ++ image: ghcr.io/mailcow/nginx:1.30.4 + dns: + - ${IPV4_NETWORK:-172.22.1}.254 + environment: diff --git a/tasks/mailcow__mailcow-dockerized-7358/tests/test.sh b/tasks/mailcow__mailcow-dockerized-7358/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7ef01388bb1e73ac7d0ef48601901adf0b628cc1 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7358/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 4b62af9d023d5bda57f85293513631013eccd8df > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "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-7358/tests/verifier.py b/tasks/mailcow__mailcow-dockerized-7358/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7358/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "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-7367/environment/Dockerfile b/tasks/mailcow__mailcow-dockerized-7367/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..f7d991eff136d4900e40656601019e1351e02495 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7367/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git 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 4b62af9d023d5bda57f85293513631013eccd8df 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4b62af9d023d5bda57f85293513631013eccd8df \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4b62af9d023d5bda57f85293513631013eccd8df \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -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-7367/instruction.md b/tasks/mailcow__mailcow-dockerized-7367/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3859d6e7765547e7bd9775d2c645cbdd5f46af05 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7367/instruction.md @@ -0,0 +1,44 @@ +# Issue + +**Title:** fix: restore subject display in quarantine overview + +## 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 + +. + +Since moving to rspamd's multipart metadata_exporter with 2026-07, subject is a JSON encoded UTF-8 string and no longer a MIME encoded ASCII string. +While `iconv_mime_decode` returns the unchanged string for plain ASCII subjects, it errors out returning `false` If the quarantined email has UTF-8 glyphs (diacritics, emoji, ...) in its subject. This causes an empty subject to be stored in the quarantine database table. +This PR simply removes the now obsolete `iconv_mime_decode` in the quarantine processor (`pipe.php`). The same code path in `pushover.php`was also fixed. + +### Affected Containers + +- rspamd-mailcow + +## Did you run tests? + +Developed and tested on a staging mailcow stack and already deployed to production. + +### What did you test? + +Whether the subject of quarantined emails is correctly shown in the quarantine overview (both for users and admins). + +### What were the final results? (Awaited, got) + +After 2026-07 update before fix: empty subjects in quarantine overview +Awaited: subject correctly displayed in quarantine overview +Got: subject correctly displayed in quarantine overview +quarantine + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4b62af9d023d`. Edit files in place; the verifier captures your changes via `git diff` 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-7367/solution/patch.diff b/tasks/mailcow__mailcow-dockerized-7367/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..0751881e15d5bdbac611fada1f0866ccc8582511 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7367/solution/patch.diff @@ -0,0 +1,26 @@ +diff --git a/data/conf/rspamd/meta_exporter/pipe.php b/data/conf/rspamd/meta_exporter/pipe.php +index 0a9ed59e..28b06d3d 100644 +--- a/data/conf/rspamd/meta_exporter/pipe.php ++++ b/data/conf/rspamd/meta_exporter/pipe.php +@@ -53,7 +53,7 @@ $raw_data = mb_convert_encoding($raw_data_content, 'HTML-ENTITIES', "UTF-8"); + $raw_size = (int)$_FILES['message']['size']; + + $qid = $meta['qid'] ?? 'unknown'; +-$subject = iconv_mime_decode($meta['subject'] ?? ''); ++$subject = $meta['subject'] ?? ''; + $score = $meta['score'] ?? 0; + $rcpts = $meta['rcpt'] ?? array(); + $user = $meta['user'] ?? 'unknown'; +diff --git a/data/conf/rspamd/meta_exporter/pushover.php b/data/conf/rspamd/meta_exporter/pushover.php +index a2cd0995..188d0a57 100644 +--- a/data/conf/rspamd/meta_exporter/pushover.php ++++ b/data/conf/rspamd/meta_exporter/pushover.php +@@ -50,7 +50,7 @@ $qid = $meta['qid'] ?? 'unknown'; + $rcpts = $meta['rcpt'] ?? array(); + $sender = $meta['from'] ?? ''; + $ip = $meta['ip'] ?? 'unknown'; +-$subject = iconv_mime_decode($meta['subject'] ?? ''); ++$subject = $meta['subject'] ?? ''; + $messageid= $meta['message_id'] ?? ''; + $priority = 0; + diff --git a/tasks/mailcow__mailcow-dockerized-7367/solution/solve.sh b/tasks/mailcow__mailcow-dockerized-7367/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7367/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo 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-7367/task.toml b/tasks/mailcow__mailcow-dockerized-7367/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..068f39e6ae0478c585e8a57f88f2f5ec70eeecfb --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7367/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/mailcow__mailcow-dockerized-7367" +description = "fix: restore subject display in quarantine overview" + +[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 = "4b62af9d023d5bda57f85293513631013eccd8df" +reference = "https://github.com/mailcow/mailcow-dockerized/pull/7367" +source_access = "auto" +built_at = "2026-11-16T16:09:53.133621+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:98d9243f5f038afe63824b03068216dbc3fdf53a7cf612f1b0072c7270ed7d94" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-07-28T08:54:23Z" +diff_format = "unified" +context_files = [ + "data/conf/rspamd/meta_exporter/pipe.php", + "data/conf/rspamd/meta_exporter/pushover.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.466499+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:d797316cda26c88c8082952a3fed2131f2fefd046a1d056ca38bb2fd825dc74f" +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-7367/tests/capture.py b/tasks/mailcow__mailcow-dockerized-7367/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7367/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture 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-7367/tests/instruction.md b/tasks/mailcow__mailcow-dockerized-7367/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3859d6e7765547e7bd9775d2c645cbdd5f46af05 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7367/tests/instruction.md @@ -0,0 +1,44 @@ +# Issue + +**Title:** fix: restore subject display in quarantine overview + +## 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 + +. + +Since moving to rspamd's multipart metadata_exporter with 2026-07, subject is a JSON encoded UTF-8 string and no longer a MIME encoded ASCII string. +While `iconv_mime_decode` returns the unchanged string for plain ASCII subjects, it errors out returning `false` If the quarantined email has UTF-8 glyphs (diacritics, emoji, ...) in its subject. This causes an empty subject to be stored in the quarantine database table. +This PR simply removes the now obsolete `iconv_mime_decode` in the quarantine processor (`pipe.php`). The same code path in `pushover.php`was also fixed. + +### Affected Containers + +- rspamd-mailcow + +## Did you run tests? + +Developed and tested on a staging mailcow stack and already deployed to production. + +### What did you test? + +Whether the subject of quarantined emails is correctly shown in the quarantine overview (both for users and admins). + +### What were the final results? (Awaited, got) + +After 2026-07 update before fix: empty subjects in quarantine overview +Awaited: subject correctly displayed in quarantine overview +Got: subject correctly displayed in quarantine overview +quarantine + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4b62af9d023d`. Edit files in place; the verifier captures your changes via `git diff` 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-7367/tests/oracle.patch b/tasks/mailcow__mailcow-dockerized-7367/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..0751881e15d5bdbac611fada1f0866ccc8582511 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7367/tests/oracle.patch @@ -0,0 +1,26 @@ +diff --git a/data/conf/rspamd/meta_exporter/pipe.php b/data/conf/rspamd/meta_exporter/pipe.php +index 0a9ed59e..28b06d3d 100644 +--- a/data/conf/rspamd/meta_exporter/pipe.php ++++ b/data/conf/rspamd/meta_exporter/pipe.php +@@ -53,7 +53,7 @@ $raw_data = mb_convert_encoding($raw_data_content, 'HTML-ENTITIES', "UTF-8"); + $raw_size = (int)$_FILES['message']['size']; + + $qid = $meta['qid'] ?? 'unknown'; +-$subject = iconv_mime_decode($meta['subject'] ?? ''); ++$subject = $meta['subject'] ?? ''; + $score = $meta['score'] ?? 0; + $rcpts = $meta['rcpt'] ?? array(); + $user = $meta['user'] ?? 'unknown'; +diff --git a/data/conf/rspamd/meta_exporter/pushover.php b/data/conf/rspamd/meta_exporter/pushover.php +index a2cd0995..188d0a57 100644 +--- a/data/conf/rspamd/meta_exporter/pushover.php ++++ b/data/conf/rspamd/meta_exporter/pushover.php +@@ -50,7 +50,7 @@ $qid = $meta['qid'] ?? 'unknown'; + $rcpts = $meta['rcpt'] ?? array(); + $sender = $meta['from'] ?? ''; + $ip = $meta['ip'] ?? 'unknown'; +-$subject = iconv_mime_decode($meta['subject'] ?? ''); ++$subject = $meta['subject'] ?? ''; + $messageid= $meta['message_id'] ?? ''; + $priority = 0; + diff --git a/tasks/mailcow__mailcow-dockerized-7367/tests/test.sh b/tasks/mailcow__mailcow-dockerized-7367/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7ef01388bb1e73ac7d0ef48601901adf0b628cc1 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7367/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 4b62af9d023d5bda57f85293513631013eccd8df > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "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-7367/tests/verifier.py b/tasks/mailcow__mailcow-dockerized-7367/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7367/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "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-7385/environment/Dockerfile b/tasks/mailcow__mailcow-dockerized-7385/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d7d0234054c7a2f53390dcec5c296863e9c7bf6a --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7385/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git 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 f4961c4023596e07d5d7fe73703479c5e9575fda 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard f4961c4023596e07d5d7fe73703479c5e9575fda \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base f4961c4023596e07d5d7fe73703479c5e9575fda \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -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-7385/instruction.md b/tasks/mailcow__mailcow-dockerized-7385/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d6ac8ced18327bbec2ae8e1edc436d5833af113e --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7385/instruction.md @@ -0,0 +1,38 @@ +# Issue + +**Title:** [Web] harden CORS origin matching and add Vary: Origin + +## Description + +## Contribution Guidelines + +* [x] I've read the contribution guidelines and wholeheartedly agree them + +## What does this PR include? + +### Short Description + +Hardens CORS origin matching (builds on #7333/#7332): normalizes the stored +allowlist and the request `Origin` before comparing (legacy bare hostnames keep +working), sends no `Access-Control-Allow-Origin` for disallowed origins instead of +echoing the first configured one, and adds `Vary: Origin`. + +### Affected Containers + +- php-fpm-mailcow + +## Did you run tests? + +### What did you tested? + +Probed `/api/v1` CORS headers on a live instance with allowed, disallowed, malformed +and preflight (`OPTIONS`) origins. + +### What were the final results? (Awaited, got) + +All as awaited: allowed origin echoed exactly + `Vary: Origin`; disallowed/malformed +never reflected; preflight returns the expected methods/headers. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `f4961c402359`. Edit files in place; the verifier captures your changes via `git diff` 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-7385/solution/patch.diff b/tasks/mailcow__mailcow-dockerized-7385/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..ac1ed71fb94ac6162fe012cadd81a10c5300f3df --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7385/solution/patch.diff @@ -0,0 +1,67 @@ +diff --git a/data/web/inc/functions.inc.php b/data/web/inc/functions.inc.php +index f9b0f6ab..dfd860a9 100644 +--- a/data/web/inc/functions.inc.php ++++ b/data/web/inc/functions.inc.php +@@ -75,6 +75,17 @@ function valid_origin($origin) { + $rebuilt = strtolower($parts['scheme']) . '://' . strtolower($host) . $port; + return strtolower($origin) === $rebuilt; + } ++// Bring an origin into the exact form a browser sends it (scheme://host[:port], lowercase). ++function normalize_cors_origin($origin) { ++ $origin = trim($origin); ++ if ($origin === '*') { ++ return '*'; ++ } ++ if ($origin !== '' && !preg_match('~^[a-z][a-z0-9+.-]*://~i', $origin)) { ++ $origin = 'https://' . $origin; ++ } ++ return valid_origin($origin) ? strtolower($origin) : false; ++} + // Thanks to https://stackoverflow.com/a/49373789 + // Validates exact ip matches and ip-in-cidr, ipv4 and ipv6 + function ip_acl($ip, $networks) { +@@ -2370,26 +2381,35 @@ function cors($action, $data = null) { + ); + } + +- $cors_settings = !$cors_settings ? array('allowed_origins' => $_SERVER['SERVER_NAME'], 'allowed_methods' => 'GET, POST, PUT, DELETE') : $cors_settings; +- $cors_settings['allowed_origins'] = empty($cors_settings['allowed_origins']) ? $_SERVER['SERVER_NAME'] : $cors_settings['allowed_origins']; ++ $cors_settings = !$cors_settings ? array('allowed_origins' => getBaseURL(), 'allowed_methods' => 'GET, POST, PUT, DELETE') : $cors_settings; ++ $cors_settings['allowed_origins'] = empty($cors_settings['allowed_origins']) ? getBaseURL() : $cors_settings['allowed_origins']; + $cors_settings['allowed_methods'] = empty($cors_settings['allowed_methods']) ? 'GET, POST, PUT, DELETE, OPTION' : $cors_settings['allowed_methods']; + + return $cors_settings; + break; + case "set_headers": + $cors_settings = cors('get'); ++ // normalize the stored list; it may still hold bare hostnames written before origins were validated as origins ++ $allowed_origins = array_filter(array_map('normalize_cors_origin', explode(',', $cors_settings['allowed_origins']))); ++ $origin = isset($_SERVER['HTTP_ORIGIN']) ? normalize_cors_origin($_SERVER['HTTP_ORIGIN']) : false; + // check if requested origin is in allowed origins +- $allowed_origins = explode(', ', $cors_settings['allowed_origins']); +- $cors_settings['allowed_origins'] = $allowed_origins[0]; +- if (in_array('*', $allowed_origins)){ +- $cors_settings['allowed_origins'] = '*'; +- } else if (array_key_exists('HTTP_ORIGIN', $_SERVER) && in_array($_SERVER['HTTP_ORIGIN'], $allowed_origins)) { +- $cors_settings['allowed_origins'] = $_SERVER['HTTP_ORIGIN']; ++ $allow_origin = null; ++ if (in_array('*', $allowed_origins, true)) { ++ $allow_origin = '*'; ++ } else if ($origin !== false && in_array($origin, $allowed_origins, true)) { ++ $allow_origin = $origin; + } + // always allow OPTIONS for preflight request + $cors_settings["allowed_methods"] = empty($cors_settings["allowed_methods"]) ? 'OPTIONS' : $cors_settings["allowed_methods"] . ', ' . 'OPTIONS'; + +- header('Access-Control-Allow-Origin: ' . $cors_settings['allowed_origins']); ++ // a disallowed origin gets no Access-Control-Allow-Origin at all; echoing a different origin than the requesting one tells a browser nothing ++ if ($allow_origin !== null) { ++ header('Access-Control-Allow-Origin: ' . $allow_origin); ++ } ++ if ($allow_origin !== '*') { ++ // the response depends on the request origin, keep caches from mixing them up ++ header('Vary: Origin', false); ++ } + header('Access-Control-Allow-Methods: '. $cors_settings['allowed_methods']); + header('Access-Control-Allow-Headers: Accept, Content-Type, X-Api-Key, Origin'); + diff --git a/tasks/mailcow__mailcow-dockerized-7385/solution/solve.sh b/tasks/mailcow__mailcow-dockerized-7385/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7385/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo 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-7385/task.toml b/tasks/mailcow__mailcow-dockerized-7385/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..2bb4d7fbddd3aed28c0318ecfd98c136b863a636 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7385/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/mailcow__mailcow-dockerized-7385" +description = "[Web] harden CORS origin matching and add Vary: Origin" + +[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 = "f4961c4023596e07d5d7fe73703479c5e9575fda" +reference = "https://github.com/mailcow/mailcow-dockerized/pull/7385" +source_access = "auto" +built_at = "2026-11-16T16:09:53.167916+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:7bb138fbe13b539fe704bf54b811ba2ef4ec5e53675dffab4569b8516363f375" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-07-30T06:41:01Z" +diff_format = "unified" +context_files = [ + "data/web/inc/functions.inc.php", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 38 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.466987+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:687ad5d2185d0a078a2867c85d275c407c199016b4d5a82415f152ca3731b74a" +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-7385/tests/capture.py b/tasks/mailcow__mailcow-dockerized-7385/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7385/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture 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-7385/tests/instruction.md b/tasks/mailcow__mailcow-dockerized-7385/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d6ac8ced18327bbec2ae8e1edc436d5833af113e --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7385/tests/instruction.md @@ -0,0 +1,38 @@ +# Issue + +**Title:** [Web] harden CORS origin matching and add Vary: Origin + +## Description + +## Contribution Guidelines + +* [x] I've read the contribution guidelines and wholeheartedly agree them + +## What does this PR include? + +### Short Description + +Hardens CORS origin matching (builds on #7333/#7332): normalizes the stored +allowlist and the request `Origin` before comparing (legacy bare hostnames keep +working), sends no `Access-Control-Allow-Origin` for disallowed origins instead of +echoing the first configured one, and adds `Vary: Origin`. + +### Affected Containers + +- php-fpm-mailcow + +## Did you run tests? + +### What did you tested? + +Probed `/api/v1` CORS headers on a live instance with allowed, disallowed, malformed +and preflight (`OPTIONS`) origins. + +### What were the final results? (Awaited, got) + +All as awaited: allowed origin echoed exactly + `Vary: Origin`; disallowed/malformed +never reflected; preflight returns the expected methods/headers. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `f4961c402359`. Edit files in place; the verifier captures your changes via `git diff` 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-7385/tests/oracle.patch b/tasks/mailcow__mailcow-dockerized-7385/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..ac1ed71fb94ac6162fe012cadd81a10c5300f3df --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7385/tests/oracle.patch @@ -0,0 +1,67 @@ +diff --git a/data/web/inc/functions.inc.php b/data/web/inc/functions.inc.php +index f9b0f6ab..dfd860a9 100644 +--- a/data/web/inc/functions.inc.php ++++ b/data/web/inc/functions.inc.php +@@ -75,6 +75,17 @@ function valid_origin($origin) { + $rebuilt = strtolower($parts['scheme']) . '://' . strtolower($host) . $port; + return strtolower($origin) === $rebuilt; + } ++// Bring an origin into the exact form a browser sends it (scheme://host[:port], lowercase). ++function normalize_cors_origin($origin) { ++ $origin = trim($origin); ++ if ($origin === '*') { ++ return '*'; ++ } ++ if ($origin !== '' && !preg_match('~^[a-z][a-z0-9+.-]*://~i', $origin)) { ++ $origin = 'https://' . $origin; ++ } ++ return valid_origin($origin) ? strtolower($origin) : false; ++} + // Thanks to https://stackoverflow.com/a/49373789 + // Validates exact ip matches and ip-in-cidr, ipv4 and ipv6 + function ip_acl($ip, $networks) { +@@ -2370,26 +2381,35 @@ function cors($action, $data = null) { + ); + } + +- $cors_settings = !$cors_settings ? array('allowed_origins' => $_SERVER['SERVER_NAME'], 'allowed_methods' => 'GET, POST, PUT, DELETE') : $cors_settings; +- $cors_settings['allowed_origins'] = empty($cors_settings['allowed_origins']) ? $_SERVER['SERVER_NAME'] : $cors_settings['allowed_origins']; ++ $cors_settings = !$cors_settings ? array('allowed_origins' => getBaseURL(), 'allowed_methods' => 'GET, POST, PUT, DELETE') : $cors_settings; ++ $cors_settings['allowed_origins'] = empty($cors_settings['allowed_origins']) ? getBaseURL() : $cors_settings['allowed_origins']; + $cors_settings['allowed_methods'] = empty($cors_settings['allowed_methods']) ? 'GET, POST, PUT, DELETE, OPTION' : $cors_settings['allowed_methods']; + + return $cors_settings; + break; + case "set_headers": + $cors_settings = cors('get'); ++ // normalize the stored list; it may still hold bare hostnames written before origins were validated as origins ++ $allowed_origins = array_filter(array_map('normalize_cors_origin', explode(',', $cors_settings['allowed_origins']))); ++ $origin = isset($_SERVER['HTTP_ORIGIN']) ? normalize_cors_origin($_SERVER['HTTP_ORIGIN']) : false; + // check if requested origin is in allowed origins +- $allowed_origins = explode(', ', $cors_settings['allowed_origins']); +- $cors_settings['allowed_origins'] = $allowed_origins[0]; +- if (in_array('*', $allowed_origins)){ +- $cors_settings['allowed_origins'] = '*'; +- } else if (array_key_exists('HTTP_ORIGIN', $_SERVER) && in_array($_SERVER['HTTP_ORIGIN'], $allowed_origins)) { +- $cors_settings['allowed_origins'] = $_SERVER['HTTP_ORIGIN']; ++ $allow_origin = null; ++ if (in_array('*', $allowed_origins, true)) { ++ $allow_origin = '*'; ++ } else if ($origin !== false && in_array($origin, $allowed_origins, true)) { ++ $allow_origin = $origin; + } + // always allow OPTIONS for preflight request + $cors_settings["allowed_methods"] = empty($cors_settings["allowed_methods"]) ? 'OPTIONS' : $cors_settings["allowed_methods"] . ', ' . 'OPTIONS'; + +- header('Access-Control-Allow-Origin: ' . $cors_settings['allowed_origins']); ++ // a disallowed origin gets no Access-Control-Allow-Origin at all; echoing a different origin than the requesting one tells a browser nothing ++ if ($allow_origin !== null) { ++ header('Access-Control-Allow-Origin: ' . $allow_origin); ++ } ++ if ($allow_origin !== '*') { ++ // the response depends on the request origin, keep caches from mixing them up ++ header('Vary: Origin', false); ++ } + header('Access-Control-Allow-Methods: '. $cors_settings['allowed_methods']); + header('Access-Control-Allow-Headers: Accept, Content-Type, X-Api-Key, Origin'); + diff --git a/tasks/mailcow__mailcow-dockerized-7385/tests/test.sh b/tasks/mailcow__mailcow-dockerized-7385/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..38752568f53a91f7ffe7f359bf0816b4574dfb5a --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7385/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace f4961c4023596e07d5d7fe73703479c5e9575fda > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "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-7385/tests/verifier.py b/tasks/mailcow__mailcow-dockerized-7385/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7385/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "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-7386/environment/Dockerfile b/tasks/mailcow__mailcow-dockerized-7386/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..af26e1fe6a7e5b929b4b7f3e9db3055a8af0a643 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7386/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git 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 bd037d5644fa133e60909ef17d743019f67a244d 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard bd037d5644fa133e60909ef17d743019f67a244d \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base bd037d5644fa133e60909ef17d743019f67a244d \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -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-7386/instruction.md b/tasks/mailcow__mailcow-dockerized-7386/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..bdbb9e2338caf4ce91cf04a6e5577c80693b5fe6 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7386/instruction.md @@ -0,0 +1,30 @@ +# Issue + +**Title:** [Rspamd] update to 4.1.4 + +## Description + +## Contribution Guidelines + +* [x] I've read the contribution guidelines and wholeheartedly agree them + +## What does this PR include? + +### Short Description + +Updates rspamd from 4.1.0 to 4.1.4 (security + bugfixes, incl. controller auth +fail-open fix and regexp/parser hardening). No config changes. + +### Affected Containers + +- rspamd-mailcow + +## Did you run tests? + +### What did you tested? + +Built the rspamd image and ran the stack + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `bd037d5644fa`. Edit files in place; the verifier captures your changes via `git diff` 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-7386/solution/patch.diff b/tasks/mailcow__mailcow-dockerized-7386/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..5f14b12b19511ff02bbad12e584e1914aeb5800a --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7386/solution/patch.diff @@ -0,0 +1,26 @@ +diff --git a/data/Dockerfiles/rspamd/Dockerfile b/data/Dockerfiles/rspamd/Dockerfile +index d37d1226..13e56357 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_4.1.0-1~e2b0b18 ++ARG RSPAMD_VER=rspamd_4.1.4-1~beb659b + ARG CODENAME=trixie + ENV LC_ALL=C + +diff --git a/docker-compose.yml b/docker-compose.yml +index dab078c8..8b24b23c 100644 +--- a/docker-compose.yml ++++ b/docker-compose.yml +@@ -84,7 +84,7 @@ services: + - clamd + + rspamd-mailcow: +- image: ghcr.io/mailcow/rspamd:4.1.0-1 ++ image: ghcr.io/mailcow/rspamd:4.1.4-1 + stop_grace_period: 30s + depends_on: + - dovecot-mailcow diff --git a/tasks/mailcow__mailcow-dockerized-7386/solution/solve.sh b/tasks/mailcow__mailcow-dockerized-7386/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7386/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo 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-7386/task.toml b/tasks/mailcow__mailcow-dockerized-7386/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..c6594502aaf937841f5dbdb8aaa68031f89adfe9 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7386/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/mailcow__mailcow-dockerized-7386" +description = "[Rspamd] update to 4.1.4" + +[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 = "bd037d5644fa133e60909ef17d743019f67a244d" +reference = "https://github.com/mailcow/mailcow-dockerized/pull/7386" +source_access = "auto" +built_at = "2026-11-16T16:09:53.169368+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:28838fd2e6dc833efdf3297bff8086fa8cf7b73ced90187fcd84609e3e6b1e14" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-07-30T06:59:04Z" +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.467481+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:d1c7bee95a4185cc6c4d76f2b6cf9534bd28c75656e906e06d74e15783d06dea" +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-7386/tests/capture.py b/tasks/mailcow__mailcow-dockerized-7386/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7386/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture 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-7386/tests/instruction.md b/tasks/mailcow__mailcow-dockerized-7386/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..bdbb9e2338caf4ce91cf04a6e5577c80693b5fe6 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7386/tests/instruction.md @@ -0,0 +1,30 @@ +# Issue + +**Title:** [Rspamd] update to 4.1.4 + +## Description + +## Contribution Guidelines + +* [x] I've read the contribution guidelines and wholeheartedly agree them + +## What does this PR include? + +### Short Description + +Updates rspamd from 4.1.0 to 4.1.4 (security + bugfixes, incl. controller auth +fail-open fix and regexp/parser hardening). No config changes. + +### Affected Containers + +- rspamd-mailcow + +## Did you run tests? + +### What did you tested? + +Built the rspamd image and ran the stack + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `bd037d5644fa`. Edit files in place; the verifier captures your changes via `git diff` 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-7386/tests/oracle.patch b/tasks/mailcow__mailcow-dockerized-7386/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..5f14b12b19511ff02bbad12e584e1914aeb5800a --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7386/tests/oracle.patch @@ -0,0 +1,26 @@ +diff --git a/data/Dockerfiles/rspamd/Dockerfile b/data/Dockerfiles/rspamd/Dockerfile +index d37d1226..13e56357 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_4.1.0-1~e2b0b18 ++ARG RSPAMD_VER=rspamd_4.1.4-1~beb659b + ARG CODENAME=trixie + ENV LC_ALL=C + +diff --git a/docker-compose.yml b/docker-compose.yml +index dab078c8..8b24b23c 100644 +--- a/docker-compose.yml ++++ b/docker-compose.yml +@@ -84,7 +84,7 @@ services: + - clamd + + rspamd-mailcow: +- image: ghcr.io/mailcow/rspamd:4.1.0-1 ++ image: ghcr.io/mailcow/rspamd:4.1.4-1 + stop_grace_period: 30s + depends_on: + - dovecot-mailcow diff --git a/tasks/mailcow__mailcow-dockerized-7386/tests/test.sh b/tasks/mailcow__mailcow-dockerized-7386/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..08916afd6792962781ace77a94660311a4c23106 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7386/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace bd037d5644fa133e60909ef17d743019f67a244d > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "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-7386/tests/verifier.py b/tasks/mailcow__mailcow-dockerized-7386/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7386/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "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-7388/environment/Dockerfile b/tasks/mailcow__mailcow-dockerized-7388/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..1a868e91d7b350776a65f53b687c3a7e2ba94b11 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7388/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git 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 e406ecd461c8af80b75ac8f16b1f4636450e5128 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard e406ecd461c8af80b75ac8f16b1f4636450e5128 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base e406ecd461c8af80b75ac8f16b1f4636450e5128 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -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-7388/instruction.md b/tasks/mailcow__mailcow-dockerized-7388/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..11c800c437658771bcbce7e19425f4ae81f5ce9c --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7388/instruction.md @@ -0,0 +1,26 @@ +# Issue + +**Title:** [Web] Move mailcow update check to server side + +## Description + +## Contribution Guidelines + +* [x] I've read the contribution guidelines and wholeheartedly agree them + +## What does this PR include? + +### Short Description + +Moves the mailcow update check from the browser to a server-side, Redis-cached +endpoint (admin-only). Previously every dashboard load hit the GitHub API directly, +tripping the rate limit and rendering a false "update available (undefined)". +. + +### Affected Containers + +- php-fpm-mailcow + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `e406ecd461c8`. Edit files in place; the verifier captures your changes via `git diff` 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-7388/solution/patch.diff b/tasks/mailcow__mailcow-dockerized-7388/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..2c1385cd5d800674eedb405246e46d612f9adb16 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7388/solution/patch.diff @@ -0,0 +1,146 @@ +diff --git a/data/web/inc/ajax/update_check.php b/data/web/inc/ajax/update_check.php +new file mode 100644 +index 00000000..6bf01600 +--- /dev/null ++++ b/data/web/inc/ajax/update_check.php +@@ -0,0 +1,67 @@ ++ 'error', 'message' => 'access denied')); ++ exit; ++} ++ ++$owner = $GLOBALS['MAILCOW_GIT_OWNER']; ++$repo = $GLOBALS['MAILCOW_GIT_REPO']; ++$current = $GLOBALS['MAILCOW_GIT_VERSION']; ++ ++// Cache key is bound to the running version, so an update invalidates it naturally ++$cache_key = 'MAILCOW_UPDATE_CHECK/' . $current; ++ ++// Serve cached result if present (one GitHub call per TTL, not one per page load) ++$cached = $redis->get($cache_key); ++if ($cached !== false) { ++ echo $cached; ++ exit; ++} ++ ++// GitHub requires a User-Agent and rate-limits unauthenticated requests to 60/h per IP ++function github_get($url) { ++ $ch = curl_init($url); ++ curl_setopt_array($ch, array( ++ CURLOPT_RETURNTRANSFER => true, ++ CURLOPT_USERAGENT => 'mailcow-update-check', ++ CURLOPT_TIMEOUT => 10, ++ CURLOPT_HTTPHEADER => array('Accept: application/vnd.github+json'), ++ )); ++ $body = curl_exec($ch); ++ $code = curl_getinfo($ch, CURLINFO_HTTP_CODE); ++ curl_close($ch); ++ if ($body === false || $code !== 200) return false; ++ $json = json_decode($body, true); ++ return is_array($json) ? $json : false; ++} ++ ++$latest = github_get("https://api.github.com/repos/{$owner}/{$repo}/releases/latest"); ++$release = github_get("https://api.github.com/repos/{$owner}/{$repo}/releases/tags/{$current}"); ++ ++// Any failure (rate limit, offline, unexpected payload) -> honest error, cached briefly ++if ($latest === false || $release === false || ++ empty($latest['tag_name']) || empty($latest['created_at']) || empty($release['created_at'])) { ++ $result = json_encode(array('status' => 'error', 'message' => 'could not reach GitHub API')); ++ $redis->setex($cache_key, 300, $result); ++ echo $result; ++ exit; ++} ++ ++$date_latest = strtotime($latest['created_at']); ++$date_current = strtotime($release['created_at']); ++ ++if ($date_latest <= $date_current) { ++ $result = json_encode(array('status' => 'no_update')); ++} else { ++ $result = json_encode(array('status' => 'update_available', 'latest_tag' => $latest['tag_name'])); ++} ++ ++// Cache the positive result for an hour ++$redis->setex($cache_key, 3600, $result); ++echo $result; +diff --git a/data/web/js/site/dashboard.js b/data/web/js/site/dashboard.js +index aee36171..eb50d698 100644 +--- a/data/web/js/site/dashboard.js ++++ b/data/web/js/site/dashboard.js +@@ -30,7 +30,7 @@ $(document).ready(function() { + // create host cpu and mem charts + createHostCpuAndMemChart(); + // check for new version +- if (mailcow_info.branch === "master"){ ++ if (mailcow_info.branch === "master" && mailcow_cc_role === "admin"){ + check_update(mailcow_info.version_tag, mailcow_info.project_url); + } + $("#mailcow_version").click(function(){ +@@ -1669,41 +1669,26 @@ function createHostCpuAndMemChart(){ + function check_update(current_version, github_repo_url){ + if (!current_version || !github_repo_url) return false; + +- var github_account = github_repo_url.split("/")[3]; +- var github_repo_name = github_repo_url.split("/")[4]; + +- // get details about latest release +- window.fetch("https://api.github.com/repos/"+github_account+"/"+github_repo_name+"/releases/latest", {method:'GET',cache:'no-cache'}).then(function(response) { ++ window.fetch("/inc/ajax/update_check.php", {method:'GET',cache:'no-cache'}).then(function(response) { ++ if (!response.ok) throw new Error("update check returned " + response.status); + return response.json(); +- }).then(function(latest_data) { +- // get details about current release +- window.fetch("https://api.github.com/repos/"+github_account+"/"+github_repo_name+"/releases/tags/"+current_version, {method:'GET',cache:'no-cache'}).then(function(response) { +- return response.json(); +- }).then(function(current_data) { +- // compare releases +- var date_current = new Date(current_data.created_at); +- var date_latest = new Date(latest_data.created_at); +- if (date_latest.getTime() <= date_current.getTime()){ +- // no update available +- $("#mailcow_update").removeClass("text-warning text-danger").addClass("text-success"); +- $("#mailcow_update").html("" + lang_debug.no_update_available + ""); +- } else { +- // update available +- $("#mailcow_update").removeClass("text-danger text-success").addClass("text-warning"); +- $("#mailcow_update").html(lang_debug.update_available + ` `+latest_data.tag_name+``); +- $("#mailcow_update_changelog").click(function(){ +- if (mailcow_cc_role !== "admin" && mailcow_cc_role !== "domainadmin") +- return; +- +- showVersionModal("New Release " + latest_data.tag_name, latest_data.tag_name); +- }) +- } +- }).catch(err => { +- // err +- console.log(err); +- $("#mailcow_update").removeClass("text-success text-warning").addClass("text-danger"); +- $("#mailcow_update").html(""+ lang_debug.update_failed +""); +- }); ++ }).then(function(data) { ++ if (data.status === "no_update") { ++ $("#mailcow_update").removeClass("text-warning text-danger").addClass("text-success"); ++ $("#mailcow_update").html("" + lang_debug.no_update_available + ""); ++ } else if (data.status === "update_available") { ++ $("#mailcow_update").removeClass("text-danger text-success").addClass("text-warning"); ++ $("#mailcow_update").html(lang_debug.update_available + ` `+data.latest_tag+``); ++ $("#mailcow_update_changelog").click(function(){ ++ if (mailcow_cc_role !== "admin" && mailcow_cc_role !== "domainadmin") ++ return; ++ ++ showVersionModal("New Release " + data.latest_tag, data.latest_tag); ++ }) ++ } else { ++ throw new Error(data.message || "update check failed"); ++ } + }).catch(err => { + // err + console.log(err); diff --git a/tasks/mailcow__mailcow-dockerized-7388/solution/solve.sh b/tasks/mailcow__mailcow-dockerized-7388/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7388/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo 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-7388/task.toml b/tasks/mailcow__mailcow-dockerized-7388/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..766154a58f17bd486f315142608af8549fed20ae --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7388/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/mailcow__mailcow-dockerized-7388" +description = "[Web] Move mailcow update check to server side" + +[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 = "e406ecd461c8af80b75ac8f16b1f4636450e5128" +reference = "https://github.com/mailcow/mailcow-dockerized/pull/7388" +source_access = "auto" +built_at = "2026-11-16T16:09:53.166503+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:6d663673be3a5e38ee92d5e7030dee0b39510dc6bf28b6be4c67cda2e777f306" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-07-30T07:13:19Z" +diff_format = "unified" +context_files = [ + "data/web/inc/ajax/update_check.php", + "data/web/js/site/dashboard.js", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 120 +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.467979+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:dfcfceb268189a7bf0dfb99b8eb406a9862b081dd02a941808a422087020860c" +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-7388/tests/capture.py b/tasks/mailcow__mailcow-dockerized-7388/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7388/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture 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-7388/tests/instruction.md b/tasks/mailcow__mailcow-dockerized-7388/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..11c800c437658771bcbce7e19425f4ae81f5ce9c --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7388/tests/instruction.md @@ -0,0 +1,26 @@ +# Issue + +**Title:** [Web] Move mailcow update check to server side + +## Description + +## Contribution Guidelines + +* [x] I've read the contribution guidelines and wholeheartedly agree them + +## What does this PR include? + +### Short Description + +Moves the mailcow update check from the browser to a server-side, Redis-cached +endpoint (admin-only). Previously every dashboard load hit the GitHub API directly, +tripping the rate limit and rendering a false "update available (undefined)". +. + +### Affected Containers + +- php-fpm-mailcow + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `e406ecd461c8`. Edit files in place; the verifier captures your changes via `git diff` 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-7388/tests/oracle.patch b/tasks/mailcow__mailcow-dockerized-7388/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..2c1385cd5d800674eedb405246e46d612f9adb16 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7388/tests/oracle.patch @@ -0,0 +1,146 @@ +diff --git a/data/web/inc/ajax/update_check.php b/data/web/inc/ajax/update_check.php +new file mode 100644 +index 00000000..6bf01600 +--- /dev/null ++++ b/data/web/inc/ajax/update_check.php +@@ -0,0 +1,67 @@ ++ 'error', 'message' => 'access denied')); ++ exit; ++} ++ ++$owner = $GLOBALS['MAILCOW_GIT_OWNER']; ++$repo = $GLOBALS['MAILCOW_GIT_REPO']; ++$current = $GLOBALS['MAILCOW_GIT_VERSION']; ++ ++// Cache key is bound to the running version, so an update invalidates it naturally ++$cache_key = 'MAILCOW_UPDATE_CHECK/' . $current; ++ ++// Serve cached result if present (one GitHub call per TTL, not one per page load) ++$cached = $redis->get($cache_key); ++if ($cached !== false) { ++ echo $cached; ++ exit; ++} ++ ++// GitHub requires a User-Agent and rate-limits unauthenticated requests to 60/h per IP ++function github_get($url) { ++ $ch = curl_init($url); ++ curl_setopt_array($ch, array( ++ CURLOPT_RETURNTRANSFER => true, ++ CURLOPT_USERAGENT => 'mailcow-update-check', ++ CURLOPT_TIMEOUT => 10, ++ CURLOPT_HTTPHEADER => array('Accept: application/vnd.github+json'), ++ )); ++ $body = curl_exec($ch); ++ $code = curl_getinfo($ch, CURLINFO_HTTP_CODE); ++ curl_close($ch); ++ if ($body === false || $code !== 200) return false; ++ $json = json_decode($body, true); ++ return is_array($json) ? $json : false; ++} ++ ++$latest = github_get("https://api.github.com/repos/{$owner}/{$repo}/releases/latest"); ++$release = github_get("https://api.github.com/repos/{$owner}/{$repo}/releases/tags/{$current}"); ++ ++// Any failure (rate limit, offline, unexpected payload) -> honest error, cached briefly ++if ($latest === false || $release === false || ++ empty($latest['tag_name']) || empty($latest['created_at']) || empty($release['created_at'])) { ++ $result = json_encode(array('status' => 'error', 'message' => 'could not reach GitHub API')); ++ $redis->setex($cache_key, 300, $result); ++ echo $result; ++ exit; ++} ++ ++$date_latest = strtotime($latest['created_at']); ++$date_current = strtotime($release['created_at']); ++ ++if ($date_latest <= $date_current) { ++ $result = json_encode(array('status' => 'no_update')); ++} else { ++ $result = json_encode(array('status' => 'update_available', 'latest_tag' => $latest['tag_name'])); ++} ++ ++// Cache the positive result for an hour ++$redis->setex($cache_key, 3600, $result); ++echo $result; +diff --git a/data/web/js/site/dashboard.js b/data/web/js/site/dashboard.js +index aee36171..eb50d698 100644 +--- a/data/web/js/site/dashboard.js ++++ b/data/web/js/site/dashboard.js +@@ -30,7 +30,7 @@ $(document).ready(function() { + // create host cpu and mem charts + createHostCpuAndMemChart(); + // check for new version +- if (mailcow_info.branch === "master"){ ++ if (mailcow_info.branch === "master" && mailcow_cc_role === "admin"){ + check_update(mailcow_info.version_tag, mailcow_info.project_url); + } + $("#mailcow_version").click(function(){ +@@ -1669,41 +1669,26 @@ function createHostCpuAndMemChart(){ + function check_update(current_version, github_repo_url){ + if (!current_version || !github_repo_url) return false; + +- var github_account = github_repo_url.split("/")[3]; +- var github_repo_name = github_repo_url.split("/")[4]; + +- // get details about latest release +- window.fetch("https://api.github.com/repos/"+github_account+"/"+github_repo_name+"/releases/latest", {method:'GET',cache:'no-cache'}).then(function(response) { ++ window.fetch("/inc/ajax/update_check.php", {method:'GET',cache:'no-cache'}).then(function(response) { ++ if (!response.ok) throw new Error("update check returned " + response.status); + return response.json(); +- }).then(function(latest_data) { +- // get details about current release +- window.fetch("https://api.github.com/repos/"+github_account+"/"+github_repo_name+"/releases/tags/"+current_version, {method:'GET',cache:'no-cache'}).then(function(response) { +- return response.json(); +- }).then(function(current_data) { +- // compare releases +- var date_current = new Date(current_data.created_at); +- var date_latest = new Date(latest_data.created_at); +- if (date_latest.getTime() <= date_current.getTime()){ +- // no update available +- $("#mailcow_update").removeClass("text-warning text-danger").addClass("text-success"); +- $("#mailcow_update").html("" + lang_debug.no_update_available + ""); +- } else { +- // update available +- $("#mailcow_update").removeClass("text-danger text-success").addClass("text-warning"); +- $("#mailcow_update").html(lang_debug.update_available + ` `+latest_data.tag_name+``); +- $("#mailcow_update_changelog").click(function(){ +- if (mailcow_cc_role !== "admin" && mailcow_cc_role !== "domainadmin") +- return; +- +- showVersionModal("New Release " + latest_data.tag_name, latest_data.tag_name); +- }) +- } +- }).catch(err => { +- // err +- console.log(err); +- $("#mailcow_update").removeClass("text-success text-warning").addClass("text-danger"); +- $("#mailcow_update").html(""+ lang_debug.update_failed +""); +- }); ++ }).then(function(data) { ++ if (data.status === "no_update") { ++ $("#mailcow_update").removeClass("text-warning text-danger").addClass("text-success"); ++ $("#mailcow_update").html("" + lang_debug.no_update_available + ""); ++ } else if (data.status === "update_available") { ++ $("#mailcow_update").removeClass("text-danger text-success").addClass("text-warning"); ++ $("#mailcow_update").html(lang_debug.update_available + ` `+data.latest_tag+``); ++ $("#mailcow_update_changelog").click(function(){ ++ if (mailcow_cc_role !== "admin" && mailcow_cc_role !== "domainadmin") ++ return; ++ ++ showVersionModal("New Release " + data.latest_tag, data.latest_tag); ++ }) ++ } else { ++ throw new Error(data.message || "update check failed"); ++ } + }).catch(err => { + // err + console.log(err); diff --git a/tasks/mailcow__mailcow-dockerized-7388/tests/test.sh b/tasks/mailcow__mailcow-dockerized-7388/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..97bd728d2e0b158b3a2a06699036c3212b2df425 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7388/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace e406ecd461c8af80b75ac8f16b1f4636450e5128 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "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-7388/tests/verifier.py b/tasks/mailcow__mailcow-dockerized-7388/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7388/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "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-7390/environment/Dockerfile b/tasks/mailcow__mailcow-dockerized-7390/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cdc5488b76e434316d0159c35fe567e9d4a32ed7 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7390/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git 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 2d5f166ba8ca874a121506961f9cbcc39b633df3 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 2d5f166ba8ca874a121506961f9cbcc39b633df3 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 2d5f166ba8ca874a121506961f9cbcc39b633df3 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -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-7390/instruction.md b/tasks/mailcow__mailcow-dockerized-7390/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ceff38ded9789284dda456616b19f6fd5e6e6f42 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7390/instruction.md @@ -0,0 +1,43 @@ +# Issue + +**Title:** [ACME] Skip mta-sts certificate request when MTA-STS is not active for a domain + +## 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 is based on + +Fixes: +- + +### Affected Containers + + + + + +- acme-mailcow + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `2d5f166ba8ca`. Edit files in place; the verifier captures your changes via `git diff` 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-7390/solution/patch.diff b/tasks/mailcow__mailcow-dockerized-7390/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..7188efb28e2c3e89d8e58abd9a4d4600a819d73f --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7390/solution/patch.diff @@ -0,0 +1,88 @@ +diff --git a/data/Dockerfiles/acme/acme.sh b/data/Dockerfiles/acme/acme.sh +index 271de4fc..6b7b7430 100755 +--- a/data/Dockerfiles/acme/acme.sh ++++ b/data/Dockerfiles/acme/acme.sh +@@ -249,12 +249,33 @@ while true; do + done <<< "${SQL_DOMAINS}" + + if [[ ${ONLY_MAILCOW_HOSTNAME} != "y" ]]; then ++ # Fetch all domains with an active MTA-STS policy once. ++ unset MTA_STS_ACTIVE_DOMAINS ++ declare -A MTA_STS_ACTIVE_DOMAINS ++ if [[ ${AUTODISCOVER_SAN} == "y" ]]; then ++ SQL_MTA_STS_DOMAINS=$(mariadb --skip-ssl --socket=/var/run/mysqld/mysqld.sock -u ${DBUSER} -p${DBPASS} ${DBNAME} -e "SELECT domain FROM mta_sts WHERE active = 1" -Bs) ++ if [[ $? -eq 0 ]]; then ++ while read mta_sts_domain; do ++ if [[ -z "${mta_sts_domain}" ]]; then ++ # ignore empty lines ++ continue ++ fi ++ MTA_STS_ACTIVE_DOMAINS["${mta_sts_domain}"]=1 ++ done <<< "${SQL_MTA_STS_DOMAINS}" ++ fi ++ fi + for SQL_DOMAIN in "${SQL_DOMAIN_ARR[@]}"; do + unset VALIDATED_CONFIG_DOMAINS_SUBDOMAINS + declare -a VALIDATED_CONFIG_DOMAINS_SUBDOMAINS + for SUBDOMAIN in "${ADDITIONAL_WC_ARR[@]}"; do + FULL_SUBDOMAIN="${SUBDOMAIN}.${SQL_DOMAIN}" + ++ # Skip mta-sts subdomain unless MTA-STS is enabled (active) for this domain ++ if [[ "${SUBDOMAIN}" == "mta-sts" && -z "${MTA_STS_ACTIVE_DOMAINS[${SQL_DOMAIN}]}" ]]; then ++ log_f "MTA-STS is not enabled for ${SQL_DOMAIN} - skipping mta-sts subdomain certificate" ++ continue ++ fi ++ + # Skip if subdomain matches MAILCOW_HOSTNAME + if [[ "${FULL_SUBDOMAIN}" == "${MAILCOW_HOSTNAME}" ]]; then + continue +diff --git a/data/web/lang/lang.de-de.json b/data/web/lang/lang.de-de.json +index c19eb209..28ad0d72 100644 +--- a/data/web/lang/lang.de-de.json ++++ b/data/web/lang/lang.de-de.json +@@ -728,6 +728,7 @@ + "mta_sts_mx": "MX-Server", + "mta_sts_mx_info": "Erlaubt das Senden nur an explizit aufgeführte Mailserver-Hostnamen; der sendende MTA überprüft, ob der DNS-MX-Hostname mit der Richtlinienliste übereinstimmt, und erlaubt die Zustellung nur mit einem gültigen TLS-Zertifikat (schützt vor MITM).", + "mta_sts_mx_notice": "Es können mehrere MX-Server angegeben werden (durch Kommas getrennt).", ++ "mta_sts_active_info": "Wenn nicht angehakt, wird die MTA-STS-Richtlinie nicht veröffentlicht und für die mta-sts-Subdomain kein Zertifikat über ACME angefordert.", + "multiple_bookings": "Mehrfaches Buchen", + "nexthop": "Next Hop", + "none_inherit": "Keine Auswahl / Erben", +diff --git a/data/web/lang/lang.en-gb.json b/data/web/lang/lang.en-gb.json +index 873d7b98..b8a11e5a 100644 +--- a/data/web/lang/lang.en-gb.json ++++ b/data/web/lang/lang.en-gb.json +@@ -728,6 +728,7 @@ + "mta_sts_mx": "MX server", + "mta_sts_mx_info": "Allows sending only to explicitly listed mail server hostnames; the sending MTA checks if the DNS MX hostname matches the policy list, and only allows delivery with a valid TLS certificate (guards against MITM).", + "mta_sts_mx_notice": "Multiple MX servers can be specified (separated by commas).", ++ "mta_sts_active_info": "If unchecked, the MTA-STS policy will not be published and no certificate will be requested for the mta-sts subdomain via ACME.", + "multiple_bookings": "Multiple bookings", + "none_inherit": "None / Inherit", + "nexthop": "Next hop", +diff --git a/data/web/templates/edit/domain.twig b/data/web/templates/edit/domain.twig +index 83353079..45ec654c 100644 +--- a/data/web/templates/edit/domain.twig ++++ b/data/web/templates/edit/domain.twig +@@ -340,7 +340,7 @@ +
+
+
+- ++ +
+
+
+diff --git a/docker-compose.yml b/docker-compose.yml +index 76359151..4742fef1 100644 +--- a/docker-compose.yml ++++ b/docker-compose.yml +@@ -465,7 +465,7 @@ services: + condition: service_started + unbound-mailcow: + condition: service_healthy +- image: ghcr.io/mailcow/acme:1.97 ++ image: ghcr.io/mailcow/acme:1.98 + dns: + - ${IPV4_NETWORK:-172.22.1}.254 + environment: diff --git a/tasks/mailcow__mailcow-dockerized-7390/solution/solve.sh b/tasks/mailcow__mailcow-dockerized-7390/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7390/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo 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-7390/task.toml b/tasks/mailcow__mailcow-dockerized-7390/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..dd980bffdedad1819362461027855fdb1a2c81c9 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7390/task.toml @@ -0,0 +1,72 @@ +version = "1.0" + +[task] +name = "trending/mailcow__mailcow-dockerized-7390" +description = "[ACME] Skip mta-sts certificate request when MTA-STS is not active for a domain" + +[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 = "2d5f166ba8ca874a121506961f9cbcc39b633df3" +reference = "https://github.com/mailcow/mailcow-dockerized/pull/7390" +source_access = "auto" +built_at = "2026-11-16T16:09:53.159895+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:6c15a2c6ec5bfb823194ab9c43b4d05db613a4e3c96927515cad3502b01132c0" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-07-30T08:44:24Z" +diff_format = "unified" +context_files = [ + "data/Dockerfiles/acme/acme.sh", + "data/web/lang/lang.de-de.json", + "data/web/lang/lang.en-gb.json", + "data/web/templates/edit/domain.twig", + "docker-compose.yml", +] +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.468500+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:3cf79306878a12799a1d3612ad4ecf56cd58b2f736dc34c25de622c37920a96f" +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-7390/tests/capture.py b/tasks/mailcow__mailcow-dockerized-7390/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7390/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture 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-7390/tests/instruction.md b/tasks/mailcow__mailcow-dockerized-7390/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ceff38ded9789284dda456616b19f6fd5e6e6f42 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7390/tests/instruction.md @@ -0,0 +1,43 @@ +# Issue + +**Title:** [ACME] Skip mta-sts certificate request when MTA-STS is not active for a domain + +## 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 is based on + +Fixes: +- + +### Affected Containers + + + + + +- acme-mailcow + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `2d5f166ba8ca`. Edit files in place; the verifier captures your changes via `git diff` 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-7390/tests/oracle.patch b/tasks/mailcow__mailcow-dockerized-7390/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..7188efb28e2c3e89d8e58abd9a4d4600a819d73f --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7390/tests/oracle.patch @@ -0,0 +1,88 @@ +diff --git a/data/Dockerfiles/acme/acme.sh b/data/Dockerfiles/acme/acme.sh +index 271de4fc..6b7b7430 100755 +--- a/data/Dockerfiles/acme/acme.sh ++++ b/data/Dockerfiles/acme/acme.sh +@@ -249,12 +249,33 @@ while true; do + done <<< "${SQL_DOMAINS}" + + if [[ ${ONLY_MAILCOW_HOSTNAME} != "y" ]]; then ++ # Fetch all domains with an active MTA-STS policy once. ++ unset MTA_STS_ACTIVE_DOMAINS ++ declare -A MTA_STS_ACTIVE_DOMAINS ++ if [[ ${AUTODISCOVER_SAN} == "y" ]]; then ++ SQL_MTA_STS_DOMAINS=$(mariadb --skip-ssl --socket=/var/run/mysqld/mysqld.sock -u ${DBUSER} -p${DBPASS} ${DBNAME} -e "SELECT domain FROM mta_sts WHERE active = 1" -Bs) ++ if [[ $? -eq 0 ]]; then ++ while read mta_sts_domain; do ++ if [[ -z "${mta_sts_domain}" ]]; then ++ # ignore empty lines ++ continue ++ fi ++ MTA_STS_ACTIVE_DOMAINS["${mta_sts_domain}"]=1 ++ done <<< "${SQL_MTA_STS_DOMAINS}" ++ fi ++ fi + for SQL_DOMAIN in "${SQL_DOMAIN_ARR[@]}"; do + unset VALIDATED_CONFIG_DOMAINS_SUBDOMAINS + declare -a VALIDATED_CONFIG_DOMAINS_SUBDOMAINS + for SUBDOMAIN in "${ADDITIONAL_WC_ARR[@]}"; do + FULL_SUBDOMAIN="${SUBDOMAIN}.${SQL_DOMAIN}" + ++ # Skip mta-sts subdomain unless MTA-STS is enabled (active) for this domain ++ if [[ "${SUBDOMAIN}" == "mta-sts" && -z "${MTA_STS_ACTIVE_DOMAINS[${SQL_DOMAIN}]}" ]]; then ++ log_f "MTA-STS is not enabled for ${SQL_DOMAIN} - skipping mta-sts subdomain certificate" ++ continue ++ fi ++ + # Skip if subdomain matches MAILCOW_HOSTNAME + if [[ "${FULL_SUBDOMAIN}" == "${MAILCOW_HOSTNAME}" ]]; then + continue +diff --git a/data/web/lang/lang.de-de.json b/data/web/lang/lang.de-de.json +index c19eb209..28ad0d72 100644 +--- a/data/web/lang/lang.de-de.json ++++ b/data/web/lang/lang.de-de.json +@@ -728,6 +728,7 @@ + "mta_sts_mx": "MX-Server", + "mta_sts_mx_info": "Erlaubt das Senden nur an explizit aufgeführte Mailserver-Hostnamen; der sendende MTA überprüft, ob der DNS-MX-Hostname mit der Richtlinienliste übereinstimmt, und erlaubt die Zustellung nur mit einem gültigen TLS-Zertifikat (schützt vor MITM).", + "mta_sts_mx_notice": "Es können mehrere MX-Server angegeben werden (durch Kommas getrennt).", ++ "mta_sts_active_info": "Wenn nicht angehakt, wird die MTA-STS-Richtlinie nicht veröffentlicht und für die mta-sts-Subdomain kein Zertifikat über ACME angefordert.", + "multiple_bookings": "Mehrfaches Buchen", + "nexthop": "Next Hop", + "none_inherit": "Keine Auswahl / Erben", +diff --git a/data/web/lang/lang.en-gb.json b/data/web/lang/lang.en-gb.json +index 873d7b98..b8a11e5a 100644 +--- a/data/web/lang/lang.en-gb.json ++++ b/data/web/lang/lang.en-gb.json +@@ -728,6 +728,7 @@ + "mta_sts_mx": "MX server", + "mta_sts_mx_info": "Allows sending only to explicitly listed mail server hostnames; the sending MTA checks if the DNS MX hostname matches the policy list, and only allows delivery with a valid TLS certificate (guards against MITM).", + "mta_sts_mx_notice": "Multiple MX servers can be specified (separated by commas).", ++ "mta_sts_active_info": "If unchecked, the MTA-STS policy will not be published and no certificate will be requested for the mta-sts subdomain via ACME.", + "multiple_bookings": "Multiple bookings", + "none_inherit": "None / Inherit", + "nexthop": "Next hop", +diff --git a/data/web/templates/edit/domain.twig b/data/web/templates/edit/domain.twig +index 83353079..45ec654c 100644 +--- a/data/web/templates/edit/domain.twig ++++ b/data/web/templates/edit/domain.twig +@@ -340,7 +340,7 @@ +
+
+
+- ++ +
+
+
+diff --git a/docker-compose.yml b/docker-compose.yml +index 76359151..4742fef1 100644 +--- a/docker-compose.yml ++++ b/docker-compose.yml +@@ -465,7 +465,7 @@ services: + condition: service_started + unbound-mailcow: + condition: service_healthy +- image: ghcr.io/mailcow/acme:1.97 ++ image: ghcr.io/mailcow/acme:1.98 + dns: + - ${IPV4_NETWORK:-172.22.1}.254 + environment: diff --git a/tasks/mailcow__mailcow-dockerized-7390/tests/test.sh b/tasks/mailcow__mailcow-dockerized-7390/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..874868663de0226cd36776236869003f2a93c960 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7390/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 2d5f166ba8ca874a121506961f9cbcc39b633df3 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "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-7390/tests/verifier.py b/tasks/mailcow__mailcow-dockerized-7390/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7390/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "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-7394/environment/Dockerfile b/tasks/mailcow__mailcow-dockerized-7394/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..1c3a85087178018a3c84af7b65e4d2a3d3b8767a --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7394/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git 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 8b456a33e79fe638af9da473c98af1991adef00d 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 8b456a33e79fe638af9da473c98af1991adef00d \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 8b456a33e79fe638af9da473c98af1991adef00d \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -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-7394/instruction.md b/tasks/mailcow__mailcow-dockerized-7394/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d2a349601f3a14419f129cd84c8c05a21fef3c9f --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7394/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 `8b456a33e79f`. Edit files in place; the verifier captures your changes via `git diff` 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-7394/solution/patch.diff b/tasks/mailcow__mailcow-dockerized-7394/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..064497e9f4e885a6bcc625ba129f87aa4842bc28 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7394/solution/patch.diff @@ -0,0 +1,199 @@ +diff --git a/data/conf/postfix/postscreen_access.cidr b/data/conf/postfix/postscreen_access.cidr +index 6fcedff9..3801fe31 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 Wed Jul 1 00:51:20 UTC 2026 ++# Whitelist generated by Postwhite v3.4 on Sat Aug 1 00:35:20 UTC 2026 + # https://github.com/stevejenkins/postwhite/ +-# 2251 total rules ++# 2256 total rules + 2a00:1450:4000::/36 permit + 2a00:1450:4864::/56 permit + 2a01:111:f400::/48 permit +@@ -29,6 +29,7 @@ + 2a01:b747:3004:200::/56 permit + 2a01:b747:3005:200::/56 permit + 2a01:b747:3006:200::/56 permit ++2a01:b747:3007::/56 permit + 2a02:a60:0:5::/64 permit + 2a0f:f640::/56 permit + 2c0f:fb50:4000::/36 permit +@@ -56,7 +57,14 @@ + 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.240/29 permit ++8.39.54.250/31 permit + 8.39.144.0/24 permit ++8.40.222.0/23 permit ++8.40.222.240/29 permit ++8.40.222.250/31 permit ++8.47.10.9 permit + 12.130.86.238 permit + 13.108.16.0/20 permit + 13.110.208.0/21 permit +@@ -67,6 +75,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 +@@ -170,6 +179,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 +@@ -193,6 +203,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 +@@ -275,6 +286,7 @@ + 51.83.17.38 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 +@@ -331,6 +343,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 +@@ -397,6 +410,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 +@@ -1210,6 +1224,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 +@@ -1370,6 +1387,10 @@ + 117.120.16.0/21 permit + 119.42.242.52/31 permit + 119.42.242.156 permit ++121.244.91.31 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 +@@ -1452,7 +1473,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 +@@ -1472,6 +1507,7 @@ + 139.138.46.219 permit + 139.138.57.55 permit + 139.138.58.119 permit ++139.167.79.86 permit + 139.177.108.0/25 permit + 139.180.17.0/24 permit + 140.238.148.191 permit +@@ -1528,7 +1564,7 @@ + 149.97.173.180 permit + 149.118.160.128/25 permit + 150.136.21.199 permit +-150.171.109.183 permit ++150.171.109.72 permit + 150.230.98.160 permit + 151.145.38.14 permit + 152.67.105.195 permit +@@ -1643,6 +1679,19 @@ + 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.174.10 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 +@@ -1849,7 +1898,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 +@@ -1905,6 +1963,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 +@@ -2178,7 +2238,7 @@ + 2001:748:400:3301::4 permit + 2404:6800:4000::/36 permit + 2404:6800:4864::/56 permit +-2603:1061:14:1c2::1 permit ++2603:1061:14:75::1 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 diff --git a/tasks/mailcow__mailcow-dockerized-7394/solution/solve.sh b/tasks/mailcow__mailcow-dockerized-7394/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7394/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo 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-7394/task.toml b/tasks/mailcow__mailcow-dockerized-7394/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..3728ddcc90980ff0e3cbcf74d306d266e9f25239 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7394/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/mailcow__mailcow-dockerized-7394" +description = "[Postfix] update postscreen_access.cidr" + +[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 = "8b456a33e79fe638af9da473c98af1991adef00d" +reference = "https://github.com/mailcow/mailcow-dockerized/pull/7394" +source_access = "auto" +built_at = "2026-11-16T16:09:53.156558+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:f5756f6cdbfc67cd55546a0a2c351aec1f392c9c064192e8ec03a7142a76b135" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-08-04T16:35:48Z" +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 = 68 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.469013+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:81d87b05836862a8f7d7b9aecb3797dd6073c40d93e4b49ad029613a3e63c1f4" +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-7394/tests/capture.py b/tasks/mailcow__mailcow-dockerized-7394/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7394/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture 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-7394/tests/instruction.md b/tasks/mailcow__mailcow-dockerized-7394/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d2a349601f3a14419f129cd84c8c05a21fef3c9f --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7394/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 `8b456a33e79f`. Edit files in place; the verifier captures your changes via `git diff` 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-7394/tests/oracle.patch b/tasks/mailcow__mailcow-dockerized-7394/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..064497e9f4e885a6bcc625ba129f87aa4842bc28 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7394/tests/oracle.patch @@ -0,0 +1,199 @@ +diff --git a/data/conf/postfix/postscreen_access.cidr b/data/conf/postfix/postscreen_access.cidr +index 6fcedff9..3801fe31 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 Wed Jul 1 00:51:20 UTC 2026 ++# Whitelist generated by Postwhite v3.4 on Sat Aug 1 00:35:20 UTC 2026 + # https://github.com/stevejenkins/postwhite/ +-# 2251 total rules ++# 2256 total rules + 2a00:1450:4000::/36 permit + 2a00:1450:4864::/56 permit + 2a01:111:f400::/48 permit +@@ -29,6 +29,7 @@ + 2a01:b747:3004:200::/56 permit + 2a01:b747:3005:200::/56 permit + 2a01:b747:3006:200::/56 permit ++2a01:b747:3007::/56 permit + 2a02:a60:0:5::/64 permit + 2a0f:f640::/56 permit + 2c0f:fb50:4000::/36 permit +@@ -56,7 +57,14 @@ + 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.240/29 permit ++8.39.54.250/31 permit + 8.39.144.0/24 permit ++8.40.222.0/23 permit ++8.40.222.240/29 permit ++8.40.222.250/31 permit ++8.47.10.9 permit + 12.130.86.238 permit + 13.108.16.0/20 permit + 13.110.208.0/21 permit +@@ -67,6 +75,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 +@@ -170,6 +179,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 +@@ -193,6 +203,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 +@@ -275,6 +286,7 @@ + 51.83.17.38 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 +@@ -331,6 +343,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 +@@ -397,6 +410,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 +@@ -1210,6 +1224,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 +@@ -1370,6 +1387,10 @@ + 117.120.16.0/21 permit + 119.42.242.52/31 permit + 119.42.242.156 permit ++121.244.91.31 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 +@@ -1452,7 +1473,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 +@@ -1472,6 +1507,7 @@ + 139.138.46.219 permit + 139.138.57.55 permit + 139.138.58.119 permit ++139.167.79.86 permit + 139.177.108.0/25 permit + 139.180.17.0/24 permit + 140.238.148.191 permit +@@ -1528,7 +1564,7 @@ + 149.97.173.180 permit + 149.118.160.128/25 permit + 150.136.21.199 permit +-150.171.109.183 permit ++150.171.109.72 permit + 150.230.98.160 permit + 151.145.38.14 permit + 152.67.105.195 permit +@@ -1643,6 +1679,19 @@ + 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.174.10 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 +@@ -1849,7 +1898,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 +@@ -1905,6 +1963,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 +@@ -2178,7 +2238,7 @@ + 2001:748:400:3301::4 permit + 2404:6800:4000::/36 permit + 2404:6800:4864::/56 permit +-2603:1061:14:1c2::1 permit ++2603:1061:14:75::1 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 diff --git a/tasks/mailcow__mailcow-dockerized-7394/tests/test.sh b/tasks/mailcow__mailcow-dockerized-7394/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..d8930a8ef87faf138690f95fae2e45cedbed7fd3 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7394/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 8b456a33e79fe638af9da473c98af1991adef00d > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "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-7394/tests/verifier.py b/tasks/mailcow__mailcow-dockerized-7394/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7394/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "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-7400/environment/Dockerfile b/tasks/mailcow__mailcow-dockerized-7400/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6e5962895000e5763e24b9b920157239b6caa6e5 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7400/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git 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 f7a536d63463236973898a2fde7fb686ca82683e 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard f7a536d63463236973898a2fde7fb686ca82683e \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base f7a536d63463236973898a2fde7fb686ca82683e \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -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-7400/instruction.md b/tasks/mailcow__mailcow-dockerized-7400/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9773ee33c5155b5d099fcb0393ea0f76d9a8a464 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7400/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/matrix-auto.svg) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `f7a536d63463`. Edit files in place; the verifier captures your changes via `git diff` 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-7400/solution/patch.diff b/tasks/mailcow__mailcow-dockerized-7400/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..d187c3b5b66b30227294c55d52257f4632b8eff4 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7400/solution/patch.diff @@ -0,0 +1,46 @@ +diff --git a/data/web/lang/lang.pt-br.json b/data/web/lang/lang.pt-br.json +index db3c8cac..5645537c 100644 +--- a/data/web/lang/lang.pt-br.json ++++ b/data/web/lang/lang.pt-br.json +@@ -786,7 +786,8 @@ + "mta_sts_mx_info": "Permite envio apenas para nomes de host de servidor de email explicitamente listados; o MTA de envio verifica se o nome do host DNS MX corresponde à lista de políticas e permite entrega apenas com certificado TLS válido (protege contra MITM).", + "mta_sts_mx_notice": "Múltiplos servidores MX podem ser especificados (separados por vírgulas).", + "sender_allowed": "Permitir enviar como este alias", +- "sender_allowed_info": "Se desativado, este alias poderá apenas receber e-mails. Use a ACL de remetente para substituir essa configuração e conceder a caixas de correio específicas permissão para enviar." ++ "sender_allowed_info": "Se desativado, este alias poderá apenas receber e-mails. Use a ACL de remetente para substituir essa configuração e conceder a caixas de correio específicas permissão para enviar.", ++ "mta_sts_active_info": "Se esta opção estiver desmarcada, a política MTA-STS não será publicada e nenhum certificado será solicitado via ACME para o subdomínio mta-sts." + }, + "fido2": { + "confirm": "Confirme", +@@ -1034,7 +1035,8 @@ + "weekly": "Semanalmente", + "yes": "✓", + "iam": "Provedor de Identidade", +- "internal": "Interno" ++ "internal": "Interno", ++ "force_tfa": "A2F" + }, + "oauth2": { + "access_denied": "Faça login como proprietário da mailbox para conceder acesso via OAuth2.", +@@ -1086,7 +1088,7 @@ + "rspamd_result": "Resultado do Rspamd", + "sender": "Remetente (SMTP)", + "sender_header": "Remetente (cabeçalho “De”)", +- "settings_info": "Quantidade máxima de elementos a serem colocados em quarentena: %s
Tamanho máximo do e-mail: %s MiB", ++ "settings_info": "Número máximo de elementos em quarentena (por caixa de correio): %s
Tamanho máximo do e-mail: %s MiB", + "show_item": "Mostrar item", + "spam": "Spam", + "spam_score": "Ponto", +diff --git a/data/web/lang/lang.si-si.json b/data/web/lang/lang.si-si.json +index 39d57eb3..2deb8271 100644 +--- a/data/web/lang/lang.si-si.json ++++ b/data/web/lang/lang.si-si.json +@@ -1078,7 +1078,7 @@ + "rspamd_result": "Rezultat Rspamd", + "sender": "Pošiljatelj (SMTP)", + "sender_header": "Pošiljatelj (glava »Od«)", +- "settings_info": "Največje število elementov za karanteno: %s
Največja velikost e-pošte: %s MiB", ++ "settings_info": "Največje število elementov za karanteno (na poštni predal): %s
Največja velikost e-pošte: %s MiB", + "show_item": "Prikaži element", + "spam": "Neželena pošta", + "subj": "Zadeva", diff --git a/tasks/mailcow__mailcow-dockerized-7400/solution/solve.sh b/tasks/mailcow__mailcow-dockerized-7400/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7400/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo 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-7400/task.toml b/tasks/mailcow__mailcow-dockerized-7400/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..eb187cf6c02e9a1a046a509cc39c20b5c5a4d561 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7400/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/mailcow__mailcow-dockerized-7400" +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 = "f7a536d63463236973898a2fde7fb686ca82683e" +reference = "https://github.com/mailcow/mailcow-dockerized/pull/7400" +source_access = "auto" +built_at = "2026-11-16T16:09:53.155209+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:6078479c2d3227582ba14c34d63129a8aa6ec26f6ed24b88c9d4c89290dc646c" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-08-04T16:37:38Z" +diff_format = "unified" +context_files = [ + "data/web/lang/lang.pt-br.json", + "data/web/lang/lang.si-si.json", +] +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.469526+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:ea3087b116c6e6ef61de870e3568924eaa0b649ca901f94ab9557b8944e857f1" +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-7400/tests/capture.py b/tasks/mailcow__mailcow-dockerized-7400/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7400/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture 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-7400/tests/instruction.md b/tasks/mailcow__mailcow-dockerized-7400/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9773ee33c5155b5d099fcb0393ea0f76d9a8a464 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7400/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/matrix-auto.svg) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `f7a536d63463`. Edit files in place; the verifier captures your changes via `git diff` 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-7400/tests/oracle.patch b/tasks/mailcow__mailcow-dockerized-7400/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..d187c3b5b66b30227294c55d52257f4632b8eff4 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7400/tests/oracle.patch @@ -0,0 +1,46 @@ +diff --git a/data/web/lang/lang.pt-br.json b/data/web/lang/lang.pt-br.json +index db3c8cac..5645537c 100644 +--- a/data/web/lang/lang.pt-br.json ++++ b/data/web/lang/lang.pt-br.json +@@ -786,7 +786,8 @@ + "mta_sts_mx_info": "Permite envio apenas para nomes de host de servidor de email explicitamente listados; o MTA de envio verifica se o nome do host DNS MX corresponde à lista de políticas e permite entrega apenas com certificado TLS válido (protege contra MITM).", + "mta_sts_mx_notice": "Múltiplos servidores MX podem ser especificados (separados por vírgulas).", + "sender_allowed": "Permitir enviar como este alias", +- "sender_allowed_info": "Se desativado, este alias poderá apenas receber e-mails. Use a ACL de remetente para substituir essa configuração e conceder a caixas de correio específicas permissão para enviar." ++ "sender_allowed_info": "Se desativado, este alias poderá apenas receber e-mails. Use a ACL de remetente para substituir essa configuração e conceder a caixas de correio específicas permissão para enviar.", ++ "mta_sts_active_info": "Se esta opção estiver desmarcada, a política MTA-STS não será publicada e nenhum certificado será solicitado via ACME para o subdomínio mta-sts." + }, + "fido2": { + "confirm": "Confirme", +@@ -1034,7 +1035,8 @@ + "weekly": "Semanalmente", + "yes": "✓", + "iam": "Provedor de Identidade", +- "internal": "Interno" ++ "internal": "Interno", ++ "force_tfa": "A2F" + }, + "oauth2": { + "access_denied": "Faça login como proprietário da mailbox para conceder acesso via OAuth2.", +@@ -1086,7 +1088,7 @@ + "rspamd_result": "Resultado do Rspamd", + "sender": "Remetente (SMTP)", + "sender_header": "Remetente (cabeçalho “De”)", +- "settings_info": "Quantidade máxima de elementos a serem colocados em quarentena: %s
Tamanho máximo do e-mail: %s MiB", ++ "settings_info": "Número máximo de elementos em quarentena (por caixa de correio): %s
Tamanho máximo do e-mail: %s MiB", + "show_item": "Mostrar item", + "spam": "Spam", + "spam_score": "Ponto", +diff --git a/data/web/lang/lang.si-si.json b/data/web/lang/lang.si-si.json +index 39d57eb3..2deb8271 100644 +--- a/data/web/lang/lang.si-si.json ++++ b/data/web/lang/lang.si-si.json +@@ -1078,7 +1078,7 @@ + "rspamd_result": "Rezultat Rspamd", + "sender": "Pošiljatelj (SMTP)", + "sender_header": "Pošiljatelj (glava »Od«)", +- "settings_info": "Največje število elementov za karanteno: %s
Največja velikost e-pošte: %s MiB", ++ "settings_info": "Največje število elementov za karanteno (na poštni predal): %s
Največja velikost e-pošte: %s MiB", + "show_item": "Prikaži element", + "spam": "Neželena pošta", + "subj": "Zadeva", diff --git a/tasks/mailcow__mailcow-dockerized-7400/tests/test.sh b/tasks/mailcow__mailcow-dockerized-7400/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..505e3ccbea19e786e586670f867653b3779c95ff --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7400/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace f7a536d63463236973898a2fde7fb686ca82683e > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "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-7400/tests/verifier.py b/tasks/mailcow__mailcow-dockerized-7400/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7400/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "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-7415/environment/Dockerfile b/tasks/mailcow__mailcow-dockerized-7415/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c98b7bbaa7b76d02fc2d716acefd6e954b629a2b --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7415/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git 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 d1a2f4e168ed1a0ba0b9019c3e6b6ae13eb3382f 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard d1a2f4e168ed1a0ba0b9019c3e6b6ae13eb3382f \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base d1a2f4e168ed1a0ba0b9019c3e6b6ae13eb3382f \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -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-7415/instruction.md b/tasks/mailcow__mailcow-dockerized-7415/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c6f0cca10bca819f7c07fdb0e30efd9e69bbd84e --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7415/instruction.md @@ -0,0 +1,44 @@ +# Issue + +**Title:** [Clamd] Update to 1.4.6 + +## 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 + +Bump ClamAV from 1.4.2 to 1.4.6 to patch 8 CVEs disclosed in the 1.4.6/1.5.4 release, most notably CVE-2026-20337 and CVE-2026-20338 (high-severity DoS via crafted ZIP/PDF files, PoC public). + +The 1.4.6 source vendors a Rust dep that requires `edition2024` (Cargo ≥ 1.85), which Alpine 3.21 does not ship. The clamd build image is therefore bumped from Alpine 3.21 to Alpine 3.24. + +### Affected Containers + +- clamd-mailcow + +## Did you run tests? + +### What did you tested? + +- Image rebuild on Alpine 3.24 +- Container startup and healthcheck +- `clamd --version` / `freshclam --version` inside the container +- freshclam signature update +- Direct EICAR scan via `clamdscan` (unix socket) and clean-file scan +- clamd TCP:3310 reachability from rspamd +- End-to-end: EICAR mail piped through `rspamc symbols` (rspamd → clamd) + +### What were the final results? (Awaited, got) + +- Awaited: ClamAV 1.4.6 running, signatures loaded, EICAR flagged, mail path rejects virus. Got: exactly that. +- Container `healthy`, ClamAV 1.4.6 on Alpine 3.24.1, signatures up-to-date. +- Direct EICAR scan → `Eicar-Test-Signature FOUND`; clean file → `OK`. +- End-to-end EICAR via rspamc → `Symbol: VIRUS_FOUND (2000.00)`, `Action: reject`. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d1a2f4e168ed`. Edit files in place; the verifier captures your changes via `git diff` 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-7415/solution/patch.diff b/tasks/mailcow__mailcow-dockerized-7415/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..09121b46cbbf49dfe933e2c709d569861fff39fb --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7415/solution/patch.diff @@ -0,0 +1,36 @@ +diff --git a/data/Dockerfiles/clamd/Dockerfile b/data/Dockerfiles/clamd/Dockerfile +index e60e7eef..5f444a8f 100644 +--- a/data/Dockerfiles/clamd/Dockerfile ++++ b/data/Dockerfiles/clamd/Dockerfile +@@ -1,7 +1,7 @@ +-FROM alpine:3.21 AS builder ++FROM alpine:3.24 AS builder + + WORKDIR /src +-ENV CLAMD_VERSION=1.4.2 ++ENV CLAMD_VERSION=1.4.6 + + RUN apk upgrade --no-cache \ + && apk add --update --no-cache \ +@@ -68,7 +68,7 @@ RUN wget -P /src https://www.clamav.net/downloads/production/clamav-${CLAMD_VERS + "/clamav/etc/clamav/clamav-milter.conf.sample" > "/clamav/etc/clamav/clamav-milter.conf" || exit 1 + + +-FROM alpine:3.21 ++FROM alpine:3.24 + + LABEL maintainer = "The Infrastructure Company GmbH " + +diff --git a/docker-compose.yml b/docker-compose.yml +index 4742fef1..07c738e4 100644 +--- a/docker-compose.yml ++++ b/docker-compose.yml +@@ -65,7 +65,7 @@ services: + - redis + + clamd-mailcow: +- image: ghcr.io/mailcow/clamd:1.71 ++ image: ghcr.io/mailcow/clamd:1.4.6-1 + restart: always + depends_on: + unbound-mailcow: diff --git a/tasks/mailcow__mailcow-dockerized-7415/solution/solve.sh b/tasks/mailcow__mailcow-dockerized-7415/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7415/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo 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-7415/task.toml b/tasks/mailcow__mailcow-dockerized-7415/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..5b7f17deb23d59978f09a60852552603d5b5505c --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7415/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/mailcow__mailcow-dockerized-7415" +description = "[Clamd] Update to 1.4.6" + +[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 = "d1a2f4e168ed1a0ba0b9019c3e6b6ae13eb3382f" +reference = "https://github.com/mailcow/mailcow-dockerized/pull/7415" +source_access = "auto" +built_at = "2026-11-16T16:09:53.121065+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:12a82a330c612fdca147ea241fb5b5e6de88feea116b640db5551f30b9330604" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-08-13T11:59:13Z" +diff_format = "unified" +context_files = [ + "data/Dockerfiles/clamd/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.470039+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:8030521ad07257e1a7d50ef16792c268d7796d414bd7dd983c03a0a3b0a6cdfc" +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-7415/tests/capture.py b/tasks/mailcow__mailcow-dockerized-7415/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7415/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture 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-7415/tests/instruction.md b/tasks/mailcow__mailcow-dockerized-7415/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c6f0cca10bca819f7c07fdb0e30efd9e69bbd84e --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7415/tests/instruction.md @@ -0,0 +1,44 @@ +# Issue + +**Title:** [Clamd] Update to 1.4.6 + +## 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 + +Bump ClamAV from 1.4.2 to 1.4.6 to patch 8 CVEs disclosed in the 1.4.6/1.5.4 release, most notably CVE-2026-20337 and CVE-2026-20338 (high-severity DoS via crafted ZIP/PDF files, PoC public). + +The 1.4.6 source vendors a Rust dep that requires `edition2024` (Cargo ≥ 1.85), which Alpine 3.21 does not ship. The clamd build image is therefore bumped from Alpine 3.21 to Alpine 3.24. + +### Affected Containers + +- clamd-mailcow + +## Did you run tests? + +### What did you tested? + +- Image rebuild on Alpine 3.24 +- Container startup and healthcheck +- `clamd --version` / `freshclam --version` inside the container +- freshclam signature update +- Direct EICAR scan via `clamdscan` (unix socket) and clean-file scan +- clamd TCP:3310 reachability from rspamd +- End-to-end: EICAR mail piped through `rspamc symbols` (rspamd → clamd) + +### What were the final results? (Awaited, got) + +- Awaited: ClamAV 1.4.6 running, signatures loaded, EICAR flagged, mail path rejects virus. Got: exactly that. +- Container `healthy`, ClamAV 1.4.6 on Alpine 3.24.1, signatures up-to-date. +- Direct EICAR scan → `Eicar-Test-Signature FOUND`; clean file → `OK`. +- End-to-end EICAR via rspamc → `Symbol: VIRUS_FOUND (2000.00)`, `Action: reject`. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d1a2f4e168ed`. Edit files in place; the verifier captures your changes via `git diff` 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-7415/tests/oracle.patch b/tasks/mailcow__mailcow-dockerized-7415/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..09121b46cbbf49dfe933e2c709d569861fff39fb --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7415/tests/oracle.patch @@ -0,0 +1,36 @@ +diff --git a/data/Dockerfiles/clamd/Dockerfile b/data/Dockerfiles/clamd/Dockerfile +index e60e7eef..5f444a8f 100644 +--- a/data/Dockerfiles/clamd/Dockerfile ++++ b/data/Dockerfiles/clamd/Dockerfile +@@ -1,7 +1,7 @@ +-FROM alpine:3.21 AS builder ++FROM alpine:3.24 AS builder + + WORKDIR /src +-ENV CLAMD_VERSION=1.4.2 ++ENV CLAMD_VERSION=1.4.6 + + RUN apk upgrade --no-cache \ + && apk add --update --no-cache \ +@@ -68,7 +68,7 @@ RUN wget -P /src https://www.clamav.net/downloads/production/clamav-${CLAMD_VERS + "/clamav/etc/clamav/clamav-milter.conf.sample" > "/clamav/etc/clamav/clamav-milter.conf" || exit 1 + + +-FROM alpine:3.21 ++FROM alpine:3.24 + + LABEL maintainer = "The Infrastructure Company GmbH " + +diff --git a/docker-compose.yml b/docker-compose.yml +index 4742fef1..07c738e4 100644 +--- a/docker-compose.yml ++++ b/docker-compose.yml +@@ -65,7 +65,7 @@ services: + - redis + + clamd-mailcow: +- image: ghcr.io/mailcow/clamd:1.71 ++ image: ghcr.io/mailcow/clamd:1.4.6-1 + restart: always + depends_on: + unbound-mailcow: diff --git a/tasks/mailcow__mailcow-dockerized-7415/tests/test.sh b/tasks/mailcow__mailcow-dockerized-7415/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..9014e69375e9ee889417664937856adba3780420 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7415/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace d1a2f4e168ed1a0ba0b9019c3e6b6ae13eb3382f > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "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-7415/tests/verifier.py b/tasks/mailcow__mailcow-dockerized-7415/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7415/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "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-7422/environment/Dockerfile b/tasks/mailcow__mailcow-dockerized-7422/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c4fcaa3c7aa2e11ad0b26d2511b1fcf0a8c9a407 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7422/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git 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 8fb32e4b59098c0ecd307aaa817f668814e4d235 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 8fb32e4b59098c0ecd307aaa817f668814e4d235 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 8fb32e4b59098c0ecd307aaa817f668814e4d235 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -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-7422/instruction.md b/tasks/mailcow__mailcow-dockerized-7422/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a1a4795606b556a8dd03478e829650f3de2483e4 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7422/instruction.md @@ -0,0 +1,32 @@ +# Issue + +**Title:** [SOGo] Update to 5.12.10 + +## 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 + +Updates SOGo from 5.12.9 to 5.12.10. Bumps `SOGO_VERSION`/`SOPE_VERSION` in the sogo Dockerfile and the `sogo-mailcow` image tag in `docker-compose.yml` to `5.12.10-1`. + +Fixes: +- + +### Affected Containers + +- sogo-mailcow + +## Did you run tests? + +### What did you tested? + +Built the sogo container with the new version and verified SOGo starts up and the webmail interface + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `8fb32e4b5909`. Edit files in place; the verifier captures your changes via `git diff` 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-7422/solution/patch.diff b/tasks/mailcow__mailcow-dockerized-7422/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..d70b52a49629689a507206f8fd019aeae5d90b90 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7422/solution/patch.diff @@ -0,0 +1,28 @@ +diff --git a/data/Dockerfiles/sogo/Dockerfile b/data/Dockerfiles/sogo/Dockerfile +index b4b401e8..f65ec7eb 100644 +--- a/data/Dockerfiles/sogo/Dockerfile ++++ b/data/Dockerfiles/sogo/Dockerfile +@@ -12,8 +12,8 @@ FROM debian:bookworm + LABEL maintainer="The Infrastructure Company GmbH " + + ARG DEBIAN_FRONTEND=noninteractive +-ARG SOGO_VERSION=SOGo-5.12.9 +-ARG SOPE_VERSION=SOPE-5.12.9 ++ARG SOGO_VERSION=SOGo-5.12.10 ++ARG SOPE_VERSION=SOPE-5.12.10 + # Security patches to apply (space-separated commit hashes) + ARG SOGO_SECURITY_PATCHES="" + # renovate: datasource=github-releases depName=tianon/gosu versioning=semver-coerced extractVersion=^(?.*)$ +diff --git a/docker-compose.yml b/docker-compose.yml +index 07c738e4..66455c10 100644 +--- a/docker-compose.yml ++++ b/docker-compose.yml +@@ -200,7 +200,7 @@ services: + - phpfpm + + sogo-mailcow: +- image: ghcr.io/mailcow/sogo:5.12.9-1 ++ image: ghcr.io/mailcow/sogo:5.12.10-1 + environment: + - DBNAME=${DBNAME} + - DBUSER=${DBUSER} diff --git a/tasks/mailcow__mailcow-dockerized-7422/solution/solve.sh b/tasks/mailcow__mailcow-dockerized-7422/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7422/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo 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-7422/task.toml b/tasks/mailcow__mailcow-dockerized-7422/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..43d79aa348041b4ee5dbb4dcf68ada9e2100fe75 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7422/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/mailcow__mailcow-dockerized-7422" +description = "[SOGo] Update to 5.12.10" + +[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 = "8fb32e4b59098c0ecd307aaa817f668814e4d235" +reference = "https://github.com/mailcow/mailcow-dockerized/pull/7422" +source_access = "auto" +built_at = "2026-11-16T16:09:53.123011+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:8805a2cfffccf10d6370e68dad1959ef71ed09098dbddb42cb64f61a2f65c876" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-08-17T06:24:11Z" +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.470552+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:873d2c5f4a9a38ca6f4bd31666ddefeb446273f374fc0174ac11d37583519d02" +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-7422/tests/capture.py b/tasks/mailcow__mailcow-dockerized-7422/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7422/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture 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-7422/tests/instruction.md b/tasks/mailcow__mailcow-dockerized-7422/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a1a4795606b556a8dd03478e829650f3de2483e4 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7422/tests/instruction.md @@ -0,0 +1,32 @@ +# Issue + +**Title:** [SOGo] Update to 5.12.10 + +## 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 + +Updates SOGo from 5.12.9 to 5.12.10. Bumps `SOGO_VERSION`/`SOPE_VERSION` in the sogo Dockerfile and the `sogo-mailcow` image tag in `docker-compose.yml` to `5.12.10-1`. + +Fixes: +- + +### Affected Containers + +- sogo-mailcow + +## Did you run tests? + +### What did you tested? + +Built the sogo container with the new version and verified SOGo starts up and the webmail interface + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `8fb32e4b5909`. Edit files in place; the verifier captures your changes via `git diff` 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-7422/tests/oracle.patch b/tasks/mailcow__mailcow-dockerized-7422/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..d70b52a49629689a507206f8fd019aeae5d90b90 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7422/tests/oracle.patch @@ -0,0 +1,28 @@ +diff --git a/data/Dockerfiles/sogo/Dockerfile b/data/Dockerfiles/sogo/Dockerfile +index b4b401e8..f65ec7eb 100644 +--- a/data/Dockerfiles/sogo/Dockerfile ++++ b/data/Dockerfiles/sogo/Dockerfile +@@ -12,8 +12,8 @@ FROM debian:bookworm + LABEL maintainer="The Infrastructure Company GmbH " + + ARG DEBIAN_FRONTEND=noninteractive +-ARG SOGO_VERSION=SOGo-5.12.9 +-ARG SOPE_VERSION=SOPE-5.12.9 ++ARG SOGO_VERSION=SOGo-5.12.10 ++ARG SOPE_VERSION=SOPE-5.12.10 + # Security patches to apply (space-separated commit hashes) + ARG SOGO_SECURITY_PATCHES="" + # renovate: datasource=github-releases depName=tianon/gosu versioning=semver-coerced extractVersion=^(?.*)$ +diff --git a/docker-compose.yml b/docker-compose.yml +index 07c738e4..66455c10 100644 +--- a/docker-compose.yml ++++ b/docker-compose.yml +@@ -200,7 +200,7 @@ services: + - phpfpm + + sogo-mailcow: +- image: ghcr.io/mailcow/sogo:5.12.9-1 ++ image: ghcr.io/mailcow/sogo:5.12.10-1 + environment: + - DBNAME=${DBNAME} + - DBUSER=${DBUSER} diff --git a/tasks/mailcow__mailcow-dockerized-7422/tests/test.sh b/tasks/mailcow__mailcow-dockerized-7422/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..959adc2f943d477708a49ca48b7f8d46fe830938 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7422/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 8fb32e4b59098c0ecd307aaa817f668814e4d235 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "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-7422/tests/verifier.py b/tasks/mailcow__mailcow-dockerized-7422/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7422/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "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-7423/environment/Dockerfile b/tasks/mailcow__mailcow-dockerized-7423/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..268e5fd06563b31f7c50b3d6266797a95de66ec3 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7423/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git 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 f1f7a9800bec79f057e75597404ff21104b919ab 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard f1f7a9800bec79f057e75597404ff21104b919ab \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base f1f7a9800bec79f057e75597404ff21104b919ab \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -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-7423/instruction.md b/tasks/mailcow__mailcow-dockerized-7423/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..82467c084482039c4665b1a58f5abce9308b786b --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7423/instruction.md @@ -0,0 +1,26 @@ +# Issue + +**Title:** [Dovecot] Remove legacy DeltaChat auto-filing sieve rule + +## 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 + +Removes the legacy DeltaChat auto-filing rule from `global_sieve_before`. It moved every message with a `Chat-Version` header into a `DeltaChat` folder and issued `stop;`. Modern DeltaChat only checks INBOX, so filing into a subfolder hides messages from the client, and the `stop;` additionally skipped user sieve rules. + +Fixes: +- #7418 + +### Affected Containers + +- dovecot-mailcow + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `f1f7a9800bec`. Edit files in place; the verifier captures your changes via `git diff` 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-7423/solution/patch.diff b/tasks/mailcow__mailcow-dockerized-7423/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..9dbfbad3f09efc20ea517569198aae9e2c2a28bc --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7423/solution/patch.diff @@ -0,0 +1,18 @@ +diff --git a/data/conf/dovecot/global_sieve_before b/data/conf/dovecot/global_sieve_before +index 3e79ca1d..e71be510 100644 +--- a/data/conf/dovecot/global_sieve_before ++++ b/data/conf/dovecot/global_sieve_before +@@ -1,13 +1,3 @@ + # global_sieve_before script + # global_sieve_before -> user sieve_before (mailcow UI) -> user sieve_after (mailcow UI) -> global_sieve_after + +-require ["mailbox", "fileinto"]; +- +-if header :contains ["Chat-Version"] [""] { +- if mailboxexists "DeltaChat" { +- fileinto "DeltaChat"; +- } else { +- fileinto :create "DeltaChat"; +- } +- stop; +-} diff --git a/tasks/mailcow__mailcow-dockerized-7423/solution/solve.sh b/tasks/mailcow__mailcow-dockerized-7423/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7423/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo 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-7423/task.toml b/tasks/mailcow__mailcow-dockerized-7423/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..5889a30476bbcadd5e72003252556d6736a4ee21 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7423/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/mailcow__mailcow-dockerized-7423" +description = "[Dovecot] Remove legacy DeltaChat auto-filing sieve rule" + +[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 = "f1f7a9800bec79f057e75597404ff21104b919ab" +reference = "https://github.com/mailcow/mailcow-dockerized/pull/7423" +source_access = "auto" +built_at = "2026-11-16T16:09:53.124576+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:6a21799393b60c659511f66de3b927c263d33936c8061319a8bff44a92e155cf" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-08-17T06:41:18Z" +diff_format = "unified" +context_files = [ + "data/conf/dovecot/global_sieve_before", +] +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.471076+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:efa82185e806315cd6847307eb4f51c8e0d99ceeb75fcf80c92d6cd7dbe3f4a2" +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-7423/tests/capture.py b/tasks/mailcow__mailcow-dockerized-7423/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7423/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture 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-7423/tests/instruction.md b/tasks/mailcow__mailcow-dockerized-7423/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..82467c084482039c4665b1a58f5abce9308b786b --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7423/tests/instruction.md @@ -0,0 +1,26 @@ +# Issue + +**Title:** [Dovecot] Remove legacy DeltaChat auto-filing sieve rule + +## 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 + +Removes the legacy DeltaChat auto-filing rule from `global_sieve_before`. It moved every message with a `Chat-Version` header into a `DeltaChat` folder and issued `stop;`. Modern DeltaChat only checks INBOX, so filing into a subfolder hides messages from the client, and the `stop;` additionally skipped user sieve rules. + +Fixes: +- #7418 + +### Affected Containers + +- dovecot-mailcow + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `f1f7a9800bec`. Edit files in place; the verifier captures your changes via `git diff` 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-7423/tests/oracle.patch b/tasks/mailcow__mailcow-dockerized-7423/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..9dbfbad3f09efc20ea517569198aae9e2c2a28bc --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7423/tests/oracle.patch @@ -0,0 +1,18 @@ +diff --git a/data/conf/dovecot/global_sieve_before b/data/conf/dovecot/global_sieve_before +index 3e79ca1d..e71be510 100644 +--- a/data/conf/dovecot/global_sieve_before ++++ b/data/conf/dovecot/global_sieve_before +@@ -1,13 +1,3 @@ + # global_sieve_before script + # global_sieve_before -> user sieve_before (mailcow UI) -> user sieve_after (mailcow UI) -> global_sieve_after + +-require ["mailbox", "fileinto"]; +- +-if header :contains ["Chat-Version"] [""] { +- if mailboxexists "DeltaChat" { +- fileinto "DeltaChat"; +- } else { +- fileinto :create "DeltaChat"; +- } +- stop; +-} diff --git a/tasks/mailcow__mailcow-dockerized-7423/tests/test.sh b/tasks/mailcow__mailcow-dockerized-7423/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..57b563778c59190f98003bc486851f564012b74e --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7423/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace f1f7a9800bec79f057e75597404ff21104b919ab > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "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-7423/tests/verifier.py b/tasks/mailcow__mailcow-dockerized-7423/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7423/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "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-7426/environment/Dockerfile b/tasks/mailcow__mailcow-dockerized-7426/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..8c5d73b04ce9c4aaaa04cc8794660509bede8365 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7426/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git 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 b362c7105d3d8348fb150c2f09199bd9b52559c8 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard b362c7105d3d8348fb150c2f09199bd9b52559c8 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base b362c7105d3d8348fb150c2f09199bd9b52559c8 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -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-7426/instruction.md b/tasks/mailcow__mailcow-dockerized-7426/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..270e9f57060224ad9f3b63293b3c6c6ad4644a5d --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7426/instruction.md @@ -0,0 +1,24 @@ +# Issue + +**Title:** [Web] Minor hardening across web UI and nginx + +## 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 + +Minor hardening across the web UI and nginx: consistent output encoding in the dashboard log tables (`real_rip`, `msg`) and DNS diagnostics, hex-encoding of tags when serializing log messages, stopping request processing after the OAuth login redirect, and deriving `X-Real-IP` from `$remote_addr` for PHP requests. + +### Affected Containers + +- php-fpm-mailcow +- nginx-mailcow + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `b362c7105d3d`. Edit files in place; the verifier captures your changes via `git diff` 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-7426/solution/patch.diff b/tasks/mailcow__mailcow-dockerized-7426/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..adfc84a1705047ce6a4be407dfdb75b0e3f84fb1 --- /dev/null +++ b/tasks/mailcow__mailcow-dockerized-7426/solution/patch.diff @@ -0,0 +1,125 @@ +diff --git a/data/conf/nginx/templates/sites-default.conf.j2 b/data/conf/nginx/templates/sites-default.conf.j2 +index 688f2baa..842c50a5 100644 +--- a/data/conf/nginx/templates/sites-default.conf.j2 ++++ b/data/conf/nginx/templates/sites-default.conf.j2 +@@ -116,6 +116,7 @@ location ~ \.php$ { + include /etc/nginx/fastcgi_params; + fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; + fastcgi_param PATH_INFO $fastcgi_path_info; ++ fastcgi_param HTTP_X_REAL_IP $remote_addr; + # trusted internal-auth marker; empty for external clients (see nginx.conf map) + fastcgi_param SOGO_AUTH_INTERNAL $sogo_auth_internal; + fastcgi_read_timeout 3600; +diff --git a/data/web/inc/ajax/dns_diagnostics.php b/data/web/inc/ajax/dns_diagnostics.php +index 95e34e88..7ed92db7 100644 +--- a/data/web/inc/ajax/dns_diagnostics.php ++++ b/data/web/inc/ajax/dns_diagnostics.php +@@ -380,13 +380,13 @@ if (isset($_SESSION['mailcow_cc_role']) && ($_SESSION['mailcow_cc_role'] == "adm + else { + $state = state_nomatch; + } +- $state .= '
' . $current[$data_field[$current['type']]]; ++ $state .= '
' . htmlspecialchars($current[$data_field[$current['type']]]); + } + if ($current['type'] == 'TXT' && + stripos($current['txt'], 'v=dmarc') === 0 && + $record[2] == $dmarc_link) { + $current['txt'] = str_replace(' ', '', $current['txt']); +- $state = $current[$data_field[$current['type']]] . state_optional; ++ $state = htmlspecialchars($current[$data_field[$current['type']]]) . state_optional; + } + elseif ($current['type'] == 'TXT' && + stripos($current['txt'], 'v=spf') === 0 && +@@ -396,7 +396,7 @@ if (isset($_SESSION['mailcow_cc_role']) && ($_SESSION['mailcow_cc_role'] == "adm + if (in_array($ip, $rslt) && in_array(expand_ipv6($ip6), $rslt)) { + $state = state_good; + } +- $state .= '
' . $current[$data_field[$current['type']]] . state_optional; ++ $state .= '
' . htmlspecialchars($current[$data_field[$current['type']]]) . state_optional; + } + elseif ($current['type'] == 'TXT' && + stripos($current['txt'], 'v=dkim') === 0 && +@@ -426,7 +426,7 @@ if (isset($_SESSION['mailcow_cc_role']) && ($_SESSION['mailcow_cc_role'] == "adm + if ($state == state_nomatch) { + $state = array(); + foreach ($currents as $current) { +- $state[] = $current[$data_field[$current['type']]]; ++ $state[] = htmlspecialchars($current[$data_field[$current['type']]]); + } + $state = implode('
', $state); + } +@@ -436,7 +436,7 @@ if (isset($_SESSION['mailcow_cc_role']) && ($_SESSION['mailcow_cc_role'] == "adm + %s + %s + %s +- ', $record[0], $record[1], $record[2], $state); ++ ', htmlspecialchars($record[0]), htmlspecialchars($record[1]), $record[2], $state); + $record[3] = explode('
', $state); + } + +@@ -477,7 +477,7 @@ if (isset($_SESSION['mailcow_cc_role']) && ($_SESSION['mailcow_cc_role'] == "adm + } + ?> + +- .txt' type='text/csv'>Download ++ .txt' type='text/csv'>Download +